If Statements (Python)
Jump to navigation
Jump to search
This tutorial module covers conditional if…else statements in Python.
In Python, we use if to determine whether a certain condition has been satisfied.
The if statement establishing the condition is aligned to the left, and the operation dependent on the condition is indented:
a = 10 b = 20 if a < b: print("a is smaller than b")
We get:
a is smaller than b
We can use the keyword “elif” (short for “else if”) to add further conditions to be considered in sequence:
a = 20 b = 10 if a < b: print("a is smaller than b") elif a > b: print("b is smaller than a")
Returns:
b is smaller than a
We can use the keyword “else” to include any other possibilities not explicitly matched by the previous conditions:
a = 10 b = 10 if a < b: print("a is smaller than b") elif a > b: print("b is smaller than a") else: print("a is equal to b")
We get:
a is equal to b
You can establish compound conditions using logical operators like “and”:
a = 1 b = 2 if (a > 0) and (b > a): print("b is greater than zero")
We can also use “or”:
a = 1 if (a < 0) or (a > 0): print("a is not equal to zero")
Returns:
a is not equal to zero
For more, check out the w3schools page on if…else statements.