Watch video presentation and remember to subscribe to our channel;
x = 8
y = 7
if x > y:
print("The statement is true")
#It produces The statement is true
Else
As we have see in the above example, where we have a certain condition which is only printed out if the statement is true. Therefore, else is used for the alternative result when the given expression is false. Let’s have an example here;
x = 5
y = 7
if x > y:
print("The statement is true")
else:
print("The statement is false")
#It will produce The statement is false since x is not greater than y
Elif
It may come to a certain point when one wishes to print out multiple conditions. For instance, when you have a certain expression then the result is false it will execute the following expression till when it becomes true, you can use many elif statements as possible. Let’s have a example here;
x = 5
y = 7
if x > y:
print("The statement is true")
elif x == y:
print("The two numbers are equal")
In other case you may find in elif statements no expression is true therefore we use else statement to show the result if no expression is true, as follows;
x = 5
y = 7
if x > y:
print("The statement is true")
elif x == y:
print("The two numbers are equal")
else:
print("None of the above")
#you may use different values and operators and see the result
Nested if
In this situation is when you have a if statement placed within another expression with if statement. We may have this example for better understanding;
x = 5
y = 7
if x > y:
print("The statement is true")
if x == y:
print("The two numbers are equal")
else:
print("None of the above")
#Try it yourself using a different value and operator
Or/And
In the following section we will discuss this two types of operators as we had seen them in our previous tutorial. And is used to print out the results if the two expressions are true while Or is used to print out the result if one of the given expressions are true; Let’s see this cases
Case 1;
x = 5
y = 6
if x != y and y > x:
print("The two given expressions are true")
Case 2;
x = 7
y = 6
if x != y and x > y:
print("One of the given expressions is true")
#Try it yourself using different values and operator and see the result
Thanks for reading through our tutorial, hope now you fully understand the use of if statement in python. As we continue learning about python hoping to meet you in our next tutorial.