Introduction
Deciding is essential before we want to do next. In programming too, we need to make decisions and rely on them to execute the next code. The conditions determine the execution flow of the program.
In Python, if…else statement are used to make decisions. Now we’re gonna introduce you to using the if…else statement in Python. Hope you understand.
Python Conditions
1. equals: a == b
2. not equals: a != b
3. less than: a < b
4. less than or equal to: a <= b
5. greater than: a > b
6. greater than or equal to: a >= b
In if and loops, these conditions are commonly used.
Example
a = 50 b = 100 if a < b: print("a is less than b")
Output:
a is less than b
Indentation
Python defines the scope in code based on indent.
Example of a code snippet without indents:
a = 50 b = 100 if a < b: print("a is less than b") # This will cause an error.
Elif
The elif keyword indicates that if the above condition is not true, then consider this condition.
Example:
a = 50 b = 50 if a < b: print("a is less than b") elif a == b: print("a = b")
Output:
a = b
Else
The else keyword considers a completely different condition from the previous conditions.
Example:
a = 50 b = 70 if a > b: print("a is greater than b") elif a == b: print("a = b") else: print("a < b")
Output:
a < b
In this example, the if and elif conditions are not true, so it considers the else condition.
Short hand If
You can let the statement execute on the same line as if it’s only 1 line.
Example:
a = 50 b = 70 if a < b: print("a is less than b")
Output:
a is less than b
Short hand If … Else
Example:
a = 70 b = 50 print("a < b") if a < b else print("a > b")
Output:
a > b
Nested If
Example:
x = 20 if x > 5: print("Above 5") if x > 10: print("And above 10") else: print("But not above 10")
Output:
Above 5
And above 10
Conclusion
We just introduced you to how to use the if else statement in Python.
Thank you for reading!