Python If ... Else Statements: Logical Conditions and Syntax
Understand how to use if
and else
statements in Python to control the flow of your code based on logical conditions. Learn about various comparison operators such as equals, not equals, less than, and greater than, and see how these are used in conditional statements and loops.
Python If ... Else
Python supports the usual logical conditions from mathematics:
- Equals:
a == b
- Not Equals:
a != b
- Less than:
a < b
- Less than or equal to:
a <= b
- Greater than:
a > b
- Greater than or equal to:
a >= b
These conditions are used in "if statements" and loops. An "if statement" is written using the if
keyword.
If Statement
Example
a = 20
b = 30
if b > a:
print("b is greater than a")
Output
b is greater than a
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
Example (Incorrect Indentation)
a = 20
b = 30
if b > a:
print("b is greater than a") # This will raise an error
Elif Statement
The elif
keyword is Python's way of saying "if the previous conditions were not true, then try this condition".
Example
a = 25
b = 25
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Output
a and b are equal
Else Statement
The else
keyword catches anything which isn't caught by the preceding conditions.
Example
a = 30
b = 20
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output
a is greater than b
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
a = 50
b = 30
if a > b: print("a is greater than b")
Output
a is greater than b
Short Hand If ... Else
If you have only one statement to execute for each condition, you can put it all on the same line:
Example
a = 10
b = 50
print("A") if a > b else print("B")
Output
B
Multiple Conditions
Example
a = 50
b = 50
print("A") if a > b else print("=") if a == b else print("B")
Output
=
Logical Operators
Use logical operators to combine conditional statements:
And
Example
a = 60
b = 40
c = 100
if a > b and c > a:
print("Both conditions are True")
Output
Both conditions are True
Or
Example
a = 70
b = 20
c = 50
if a > b or a > c:
print("At least one of the conditions is True")
Output
At least one of the conditions is True
Not
Example
a = 25
b = 75
if not a > b:
print("a is NOT greater than b")
Output
a is NOT greater than b
Nested If Statements
You can have if statements inside if statements, this is called nested if statements.
Example
x = 45
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Output
Above ten,
and also above 20!
The pass Statement
If you have an if statement with no content, put in the pass
statement to avoid an error.
Example
a = 30
b = 60
if b > a:
pass