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.
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.
a = 50 b = 100 if a < b: print("a is less than b")
a is less than b
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.
The elif keyword indicates that if the above condition is not true, then consider this condition.
a = 50 b = 50 if a < b: print("a is less than b") elif a == b: print("a = b")
a = b
The else keyword considers a completely different condition from the previous conditions.
a = 50 b = 70 if a > b: print("a is greater than b") elif a == b: print("a = b") else: print("a < b")
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.
a = 50 b = 70 if a < b: print("a is less than b")
a is less than b
Short hand If … Else
a = 70 b = 50 print("a < b") if a < b else print("a > b")
a > b
x = 20 if x > 5: print("Above 5") if x > 10: print("And above 10") else: print("But not above 10")
And above 10
We just introduced you to how to use the if else statement in Python.
Thank you for reading!
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.