We make dozens of decisions every day: if it is raining, we take an umbrella; if the traffic light is red, we wait; if the homework is done, we go out to play. Programs work the same way: they check a situation and take different steps depending on the result. In Python this is done with conditional statements.
Comparison operators
Every decision is based on a yes-or-no question. In Python such questions are written with comparison operators, and the answer is always a Boolean value: True or False.
| Operator | Meaning | Example |
|---|---|---|
== | is equal to | 5 == 5 → True |
!= | is not equal to | 5 != 3 → True |
> | is greater than | 2 > 7 → False |
< | is less than | 2 < 7 → True |
>= | is greater than or equal to | 7 >= 7 → True |
<= | is less than or equal to | 8 <= 7 → False |
age = 14
print(age > 12)
print(age == 18)
print(age != 18)
print('Baku' == 'baku')
print(5 <= 5)Expected output
True False True False True
The if statement
After the word if comes a condition, and at the end a colon (:). If the condition is True, the indented lines below it run; if it is False, Python skips them.
temperature = 32
if temperature > 30:
print('It is hot today!')
print('Drink more water.')
print('Have a nice day.')Expected output
It is hot today! Drink more water. Have a nice day.
temperature to 20 and see how the result changes.IndentationDefinition
The spaces at the start of a line. In Python, indentation shows which lines belong together in a block. The usual size is 4 spaces. The last line in the example is not indented, so it always runs, whatever the condition.
else and elif
else says what to do when the condition is false. For example, we can check whether a number is even by looking at the remainder after dividing by 2:
number = 7
if number % 2 == 0:
print(number, 'is even')
else:
print(number, 'is odd')Expected output
7 is odd
When there are more than two choices, elif (short for “else if”) comes to the rescue. Python checks the conditions from top to bottom and runs the block of the first true one — it does not look at the rest. If none is true, the else block runs.
score = 78
if score >= 90:
grade = 'Excellent'
elif score >= 75:
grade = 'Good'
elif score >= 50:
grade = 'Satisfactory'
else:
grade = 'Try again'
print(f'Score {score}: {grade}')Expected output
Score 78: Good
score >= 75 — is used.and, or, not
A and B—Truewhen both conditions are true.A or B—Truewhen at least one condition is true.not A— flips the condition:TruebecomesFalseand vice versa.
age = 15
has_ticket = True
is_weekend = False
if age >= 12 and has_ticket:
print('You can watch the film.')
if is_weekend or age < 7:
print('Free entry!')
else:
print('Entry costs 5 AZN.')
if not is_weekend:
print('See you after school!')Expected output
You can watch the film. Entry costs 5 AZN. See you after school!
Interactive
and works like the AND gate. Try the OR and NOT gates too and compare their tables.Example: leap year
Problem
A year is a leap year if it divides by 4, but years that divide by 100 are leap years only if they also divide by 400. Write a condition that checks whether 2024 is a leap year.
Show solutionHide solution
Solution
and: year % 4 == 0 and year % 100 != 0.Add “or divides by 400” with
or: or year % 400 == 0.Parentheses keep the first part together. The result is in the code below.
year = 2024
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(year, 'is a leap year')
else:
print(year, 'is not a leap year')Expected output
2024 is a leap year
Exercise
Look at number: print positive if it is greater than zero, negative if it is less than zero and zero if it equals zero. Use if, elif and else. Change the value of number to test every branch.
number = -7
# print positive, negative or zeroExpected output
negative
Exercise
Aysel's score is score = 83 and she has done her homework (homework_done = True). First print her grade: A if the score is at least 90, B if it is at least 75, C if it is at least 50, otherwise F. Then, if the score is at least 80 and the homework is done, print Bonus star! on a separate line.
score = 83
homework_done = True
# 1) print A, B, C or F
# 2) print Bonus star! if score >= 80 and the homework is doneExpected output
B Bonus star!
Remember
- Comparison operators (
==,!=,<,>,<=,>=) returnTrueorFalse. - An
ifcondition ends with a colon, and its block is indented by 4 spaces. - In an
elifchain only the first true condition's block runs; if none is true,elseruns. andneeds both conditions to be true,orneeds at least one, andnotflips a condition.=is assignment,==is comparison.