Module 1, topic 2, week 1, Thursday
Control flow: if/else statements
Conditions, if, else, elif, nested decisions and logical operators
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 18 solved problems, ready to run and change.
topic-02-control-flow.ipynb, 48 KB
Practice notebook
The 15 practice problems with examples of input and output, a hint and a hidden solution for each.
topic-02-practice.ipynb, 29 KB
Introduction: what is control flow?
Normally, Python reads your code from the top to the bottom, one line after another. But real programs need to make decisions:
- If the user is 18 or older, allow entry. Otherwise, refuse.
- If the temperature is below 0, show "Freezing". Otherwise, show "Not freezing".
Control flow means controlling which lines of code run, depending on conditions. The if statement is the most important control flow tool, and every program you will ever write uses it.
Real-life example: If it is raining, I take an umbrella. Otherwise, I wear sunglasses. In Python that sentence becomes:
is_raining = True
if is_raining:
print("Take an umbrella")
else:
print("Wear sunglasses")Output
Take an umbrella
Change it and run: change True to False in the first line. Which message appears now?
This lesson is a beginner-friendly guide to decision-making in Python. It explains every concept (if, else, elif, indentation, nested conditions, logical operators, truthy/falsy values, and more), then walks through 18 solved problems from easy to medium-hard, followed by practice problems. The examples use numbers, text, and Boolean values only.
By the end of this lesson you will be able to:
- 1.Write a condition with comparison operators and read its True or False answer.
- 2.Use if, else and elif with the colon and the indentation in the right place.
- 3.Explain why the order of conditions in an elif chain matters, and when separate ifs are the right choice.
- 4.Combine conditions with and, or, not, chained comparisons and nested ifs.
- 5.Use truthy and falsy values, compare text and decimals safely, and read input from the user.
- 6.Solve a problem step by step and test it with boundary values.
1Conditions: the question behind every if
An if statement asks a yes/no question. In Python, the answer is a Boolean: True or False. The question is called a condition.
1.1Comparison operators
Conditions are usually built with comparison operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | equal to | 5 == 5 | True |
| != | not equal to | 5 != 3 | True |
| > | greater than | 3 > 5 | False |
| < | less than | 3 < 5 | True |
| >= | greater than or equal to | 5 >= 5 | True |
| <= | less than or equal to | 4 <= 3 | False |
print(5 == 5) # equal to
print(5 != 3) # not equal to
print(3 > 5) # greater than
print(3 < 5) # less than
print(5 >= 5) # greater than or equal to
print(4 <= 3) # less than or equal toOutput
True True False True True False
Change it and run: change the numbers so that every line prints True.
You can see the answer directly:
age = 20
print(age >= 18) # TrueOutput
True
Change it and run: set age to 18, then to 17. At which value does the answer change?
1.2= stores, == compares
age = 18
Stores. Puts 18 into the box called age.
age == 18
Asks. Is age 18? The answer is True or False.
1.3A condition is a value
The answer of a condition can be stored in a variable, like any other value. A good name makes the if read almost like a sentence.
age = 20
is_adult = age >= 18 # the answer is stored like any other value
print(is_adult)
print(type(is_adult))Output
True <class 'bool'>
Try it yourself
price = 250 and budget = 200, print three answers: is the price within the budget (<=), is the price exactly 250, and is the price different from the budget?Show a hint
print(...) with one comparison inside: <=, == and !=.Show the solution
price = 250
budget = 200
print(price <= budget)
print(price == 250)
print(price != budget)Output
False True True
2The if statement
2.1Syntax (the exact shape)
if condition:
# code that runs only when the condition is TrueThe three important parts:
if1 temperature > 30:2 print("It is a hot day!")3
- 1The keyword
if. - 2The condition, then a colon
:. The colon is required. - 3The indented block, the lines that belong to the
if.
Forgetting the colon causes a SyntaxError.
2.2Example
temperature = 35
if temperature > 30:
print("It is a hot day!")
print("Program finished")Output
It is a hot day! Program finished
Change it and run: set temperature to 20. One line disappears from the output: which one, and why?
If you change temperature to 20, the condition becomes False, so Python skips the indented line:
temperature = 20
if temperature > 30:
print("It is a hot day!")
print("Program finished")Output
Program finished
2.3How Python reads it
- Evaluate the condition (
TrueorFalse). - If
True, run the indented block. - If
False, skip the indented block and continue below it.
Step through the example, one line at a time
- 1temperature = 35
- 2
- 3if temperature > 30:
- 4 print("It is a hot day!")
- 5
- 6print("Program finished")
What Python remembers
Nothing stored yet. Press “Run next line”.
2.4Indentation (very important in Python)
Many languages use curly braces { } to group code. Python uses indentation (spaces at the start of the line).
- Use 4 spaces for each level. In Jupyter, pressing the Tab key does this for you.
- All lines in the same block must have the same indentation.
- The first line that is not indented is outside the block.
number = 10
if number > 5:
print("Line 1: inside the if")
print("Line 2: also inside the if")
print("Line 3: outside, always runs")Output
Line 1: inside the if Line 2: also inside the if Line 3: outside, always runs
Change it and run: set number to 3. Lines 1 and 2 disappear together, line 3 still prints.
if number > 5:
····print("Line 1: inside the if")
····print("Line 2: also inside the if")
print("Line 3: outside, always runs")
- Inside the block: the two lines that start with 4 spaces (shown as ····). They run only when the condition is True.
- Outside the block: the first line that is not indented. It always runs.
2.5Common indentation errors
The line under the if is not indented:
number = 10
if number > 5:
print("Hello")Error
IndentationError: expected an indented block after 'if' statement on line 3
One line of the block is indented more than the other:
number = 10
if number > 5:
print("A")
print("B")Error
IndentationError: unexpected indent
This is what mixing looks like to Python. The first print starts with four spaces, the second with a tab character. They look almost the same to you, but not to Python:
number = 10
if number > 5:
print("A")
print("B")Error
TabError: inconsistent use of tabs and spaces in indentation
Try it yourself
speed = 72. If the speed is over 60, print Slow down. After that, always print Drive safely. Then change the speed to 50 and run it again.Show a hint
print is indented under the if. The second print starts at the left edge, so it always runs.Show the solution
speed = 72
if speed > 60:
print("Slow down")
print("Drive safely")Output
Slow down Drive safely
3else and elif
3.1if ... else
The else part runs when the condition is False. Think of it as "otherwise."
if condition:
# runs when True
else:
# runs when Falseage = 17
if age >= 18:
print("You can vote.")
else:
print("You are too young to vote.")Output
You are too young to vote.
Change it and run: test the boundary: set age to 18, then 19.
Which block runs? Change the age and watch.
- if age >= 18:False
- print("You can vote.")skipped
- else:
- print("You are too young to vote.")runs
Output
You are too young to vote.
17 >= 18 is False, so Python runs the else block and skips the other one. Exactly one of the two blocks runs.
Key facts about else:
- It has no condition of its own. It simply catches "everything else."
- It must line up (same indentation) with its
if. - It also needs a colon
:. - Exactly one of the two blocks runs, never both and never neither.
3.2elif (more than two choices)
Sometimes there are more than two possibilities. elif means "else if" and lets you check another condition.
if condition1:
# runs if condition1 is True
elif condition2:
# runs if condition1 is False AND condition2 is True
elif condition3:
# ...
else:
# runs if none of the above were Truenumber = -4
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")Output
Negative
Change it and run: set number to 5, then to 0. Each value should reach a different block.
3.3How it works (very important)
Python checks the conditions from top to bottom and runs the first block whose condition is True. After that, it skips all the remaining elif and else parts.
- You can use as many
elifparts as you want. elseis optional, and when used it must be last.
Python checks from top to bottom and stops at the first True.
- if score >= 90:False print("Grade A")
- elif score >= 80:True print("Grade B")
- elif score >= 70:not checked print("Grade C")
- elif score >= 60:not checked print("Grade D")
- else: print("Grade F")
Output
Grade B
The first True is score >= 80. Python runs that block and does not even look at the lines below it.
3.4Order matters!
Look at this mistake:
score = 95
if score >= 60:
print("Grade D")
elif score >= 90:
print("Grade A") # never reached!Output
Grade D
95 >= 60 is True, so Python stops there. Always put the most specific or strictest condition first.
score = 95
if score >= 90:
print("Grade A")
elif score >= 60:
print("Grade D")Output
Grade A
Change it and run: set score to 65. Now the second block runs.
3.5if-elif-else vs. several separate ifs
These are not the same thing.
- A chain (if / elif / else): only one block can run.
- Separate if statements: each is checked independently, so several blocks can run.
number = 15
if number % 3 == 0:
print("Divisible by 3")
if number % 5 == 0:
print("Divisible by 5")Output
Divisible by 3 Divisible by 5
If we had used elif for the second one, only the first message would appear:
number = 15
if number % 3 == 0:
print("Divisible by 3")
elif number % 5 == 0:
print("Divisible by 5") # skipped: the first block already ranOutput
Divisible by 3
Use separate ifs when the checks are independent, and elif when the choices exclude each other.
The same two checks, written in two ways.
Two separate ifs: each one is checked
- if number % 3 == 0:True
- print("Divisible by 3")runs
- if number % 5 == 0:True
- print("Divisible by 5")runs
Output
Divisible by 3 Divisible by 5
A chain with elif: only one block can run
- if number % 3 == 0:True
- print("Divisible by 3")runs
- elif number % 5 == 0:not checked
- print("Divisible by 5")skipped
Output
Divisible by 3
15 is divisible by both. The separate ifs print two lines; the chain stops after the first True and prints one.
Try it yourself
hour = 14, print Good morning when the hour is before 12, Good afternoon when it is before 18, and Good evening otherwise. Then test the hours 11, 12, 17 and 18.Show a hint
if, elif and else. Because the chain goes from the smallest limit upward, one < per line is enough.Show the solution
hour = 14
if hour < 12:
print("Good morning")
elif hour < 18:
print("Good afternoon")
else:
print("Good evening")Output
Good afternoon
4Nested if and combining conditions
4.1Nested if (an if inside an if)
You can put an if inside another if to ask a second question after the first one is answered. Each level is indented further.
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("Welcome to the concert!")
else:
print("Please buy a ticket first.")
else:
print("Sorry, 18+ only.")Output
Welcome to the concert!
Change it and run: set has_ticket to False, then set age to 16. Follow which lines run each time.
The second question is asked only after the first one is answered with True.
- if age >= 18:True
- if has_ticket:True
- print("Welcome to the concert!")
- else:
- print("Please buy a ticket first.")
- else:
- print("Sorry, 18+ only.")
Output
Welcome to the concert!
The age check is True, so Python goes inside and asks the second question about the ticket.
The same concert rules without nesting. The first line now asks both questions at once:
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome to the concert!")
elif age >= 18:
print("Please buy a ticket first.")
else:
print("Sorry, 18+ only.")Output
Welcome to the concert!
4.2Combining conditions with and, or, not
| Operator | Meaning | True when... |
|---|---|---|
| and | both | both sides are True |
| or | either | at least one side is True |
| not | opposite | the condition is False |
| a | b | a and b | a or b |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
age = 25
has_id = True
if age >= 18 and has_id:
print("Entry allowed")Output
Entry allowed
Change it and run: set has_id to False. With and, one False side is enough to stop the block.
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("Weekend!")
else:
print("Weekday")Output
Weekend!
Change it and run: set day to "Sunday", then to "Monday".
is_raining = False
if not is_raining:
print("No umbrella needed")Output
No umbrella needed
4.3Chained comparisons (a Python special!)
You can write a range check the way you would in maths:
x = 15
if 10 <= x < 20:
print("x is between 10 and 20")Output
x is between 10 and 20
Change it and run: test the edges: 10, 19 and 20. Which of them are inside the range?
This is the same as x >= 10 and x < 20, only shorter.
4.4Priority of the logical operators
Python evaluates not first, then and, then or. Use parentheses to make your meaning clear:
print(True or False and False) # True (and happens first)
print((True or False) and False) # False (brackets first)Output
True False
4.5A very common mistake
It is Monday, but this program still says it is the weekend:
day = "Monday"
if day == "Saturday" or "Sunday": # WRONG (always True)
print("Weekend!")
else:
print("Weekday")Output
Weekend!
Python reads this as (day == "Saturday") or ("Sunday"), and a non-empty text counts as True. The correct way is to repeat the full comparison on both sides:
day = "Monday"
if day == "Saturday" or day == "Sunday": # RIGHT
print("Weekend!")
else:
print("Weekday")Output
Weekday
When you compare one value with several options, in is a shorter way to write the same check (you met in in Topic 1):
day = "Sunday"
if day in ("Saturday", "Sunday"):
print("Weekend!")
else:
print("Weekday")Output
Weekend!
4.6Python stops as soon as it knows the answer
With and, if the left side is False the whole condition is already False, so Python does not look at the right side. With or, if the left side is True, Python stops there too. This is useful for a safety check: below, the division never runs when count is 0, so there is no error.
total = 0
count = 0
if count != 0 and total / count > 50:
print("High average")
else:
print("No data, or a low average")Output
No data, or a low average
Change it and run: set total to 180 and count to 3. Now the right side is checked too.
Try it yourself
age = 10 and height = 128, print Can ride or Cannot ride. Then change the height to 130.Show a hint
8 <= age <= 12) and join the height check with and.Show the solution
age = 10
height = 128
if 8 <= age <= 12 and height >= 130:
print("Can ride")
else:
print("Cannot ride")Output
Cannot ride
5Truthy values, text and decimals
5.1Truthy and falsy values
An if doesn't strictly need True or False. Python can treat other values as true or false:
- Falsy (count as False):
0,0.0,""(empty text),None,False - Truthy (count as True): almost everything else, such as
5,-3,"hello",True
name = ""
if name:
print("Hello,", name)
else:
print("You didn't enter a name.")Output
You didn't enter a name.
Change it and run: put your own name between the quotes in the first line.
print(bool(0), bool(""), bool(5), bool("hi"), bool(None))Output
False False True True False
The same idea with a number: zero items means an empty cart.
items = 0
if items:
print("You have", items, "items in your cart")
else:
print("Your cart is empty")Output
Your cart is empty
Change it and run: set items to 3.
Would the if block run? Decide for each value.
1 of 10
value = 0
if value:
print("runs")5.2Comparing text (strings)
==compares text exactly, and it is case-sensitive:"Apple" == "apple"isFalse.- Convert to lowercase first to ignore the case:
answer.lower() == "yes". - Text and numbers are never equal:
"10" == 10isFalse. - Text can be compared in alphabetical order:
"apple" < "banana"isTrue.
print("Apple" == "apple") # False: capital letters matter
print("10" == 10) # False: text and a number are never equal
print("apple" < "banana") # True: alphabetical orderOutput
False False True
answer = "YES"
if answer.lower() == "yes":
print("You agreed!")Output
You agreed!
Change it and run: try "Yes", "yes" and "no".
People also type extra spaces. .strip() removes them before the comparison:
answer = " Yes "
if answer.strip().lower() == "yes":
print("You agreed!")Output
You agreed!
5.3Comparing decimals (floats)
Because computers store decimals approximately, avoid using == with them:
print(0.1 + 0.2 == 0.3) # False (!)
print(abs((0.1 + 0.2) - 0.3) < 0.000001) # TrueOutput
False True
The second line asks: "Is the difference tiny?" That is the safe way to compare decimals. abs() gives the value without a minus sign.
5.4Checking for None
result = None
if result is None:
print("No result yet")Output
No result yet
Use is None (not == None) to ask whether a variable has no value yet.
Try it yourself
" GREEN " with extra spaces and capital letters. Print Go if the color is green, however it is written, and Wait otherwise.Show a hint
color.strip().lower(), then compare it with "green".Show the solution
color = " GREEN "
if color.strip().lower() == "green":
print("Go")
else:
print("Wait")Output
Go
6Input, one-line if/else, and pass
6.1Getting input from the user
input() asks the user to type something. It always gives you text, so convert it to a number when you need one:
age = int(input("Enter your age: ")) # whole number
price = float(input("Enter price: ")) # decimal number
name = input("Enter your name: ") # stays textage = int(input("Enter your age: "))
if age >= 18:
print("Adult")
else:
print("Minor")Output
Enter your age: 20 Adult
Change it and run: type 17 in the input box, then 18.
If you skip int(...), then age >= 18 compares text with a number and Python gives a TypeError:
age = input("Enter your age: ")
if age >= 18:
print("Adult")Output
Enter your age: 20
Error
TypeError: '>=' not supported between instances of 'str' and 'int'
(If the user types letters instead of digits, int() fails too. Handling that is a later topic.)
6.2A shorter form (one-line if/else)
For simple choices, Python lets you write the whole decision on one line:
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adultOutput
adult
Change it and run: set age to 15.
The pattern is: value_if_true if condition else value_if_false. Use it only for simple cases. Normal if/else is easier to read for anything bigger. This is the same decision written the normal way:
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
print(status)Output
adult
6.3The pass placeholder
Python doesn't allow an empty block. If you want to leave a block for later, use pass ("do nothing"):
age = 30
if age > 100:
pass # I will write this part later
print("Done")Output
Done
Without pass, a comment alone is not enough. Python still expects a real line in the block:
age = 30
if age > 100:
# I will write this part later
print("Done")Error
IndentationError: expected an indented block after 'if' statement on line 3
Try it yourself
number = 7, use the one-line form to store "even" or "odd" in a variable called kind, then print a sentence like 7 is odd.Show a hint
number % 2 == 0. Pattern: kind = "even" if ... else "odd".Show the solution
number = 7
kind = "even" if number % 2 == 0 else "odd"
print(number, "is", kind)Output
7 is odd
7How to solve a problem with if/else
- Read the problem and underline what the user gives you (the inputs).
- List every possible case. What are all the different outcomes?
- Turn each case into a condition. Make sure the cases don't overlap, or decide their order.
- Choose the structure: two outcomes (
if/else), many outcomes (if/elif/else), or a second question (nestedif). - Test with boundary values, the numbers right at the edges. For "18 or older", test 17, 18, and 19. Most bugs hide at the boundaries.
age >= 18
- 15False
- 16False
- 17Falsetest
- 18Truetest
- 19Truetest
- 20True
- 21True
> where >= was needed.Try it yourself
input() and print Free delivery or Delivery: 5. Then press Check with 5 test cases: the page runs your code with 49, 50, 51 and two more amounts.Show a hint
if/else. "50 or more" is >=. With > the case 50 would fail.Show the solution
amount = int(input())
if amount >= 50:
print("Free delivery")
else:
print("Delivery: 5")Output
Delivery: 5
8Common mistakes
Everyone makes these. The red text is the real message Python shows; where there is no message, the program runs but gives a wrong answer, which is harder to notice.
= instead of ==
Wrong
age = 18
if age = 18:
print("Adult")SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Right
age = 18
if age == 18:
print("Adult")One = stores a value, two == compare. Python even suggests the fix.
Missing colon
Wrong
age = 20
if age > 18
print("Adult")SyntaxError: expected ':'
Right
age = 20
if age > 18:
print("Adult")Wrong indentation
Wrong
number = 10
if number > 5:
print("Hello")IndentationError: expected an indented block after 'if' statement on line 3
Right
number = 10
if number > 5:
print("Hello")Indent the lines of the block by 4 spaces.
Condition after else
Wrong
age = 15
if age >= 18:
print("Adult")
else age < 18:
print("Minor")SyntaxError: expected ':'
Right
if age >= 18:
print("Adult")
elif age < 18: # or just else:
print("Minor")Use elif age < 18: or just else:. An else never has a condition.
Incomplete or check
Wrong
x = 5
if x == 1 or 2:
print("x is 1 or 2")
# prints: x is 1 or 2Right
x = 5
if x == 1 or x == 2:
print("x is 1 or 2")
# prints nothingNo error message here: the wrong version prints the line even though x is 5, because 2 alone counts as True.
Comparing text to a number
Wrong
print("5" == 5) # FalseRight
print(int("5") == 5) # TrueConvert the text first, then compare.
Wrong order in elif
Wrong
score = 95
if score >= 60:
print("Grade D")
elif score >= 90:
print("Grade A") # never reached!
# prints: Grade DRight
score = 95
if score >= 90:
print("Grade A")
elif score >= 60:
print("Grade D")
# prints: Grade AStrictest condition first: >= 90 before >= 60.
Decimal equality
Wrong
print(0.1 + 0.2 == 0.3) # False
Right
print(abs((0.1 + 0.2) - 0.3) < 0.000001) # True
Compare the difference with abs().
Forgetting to convert input
Wrong
age = input("Enter your age: ")
if age >= 18:
print("Adult")TypeError: '>=' not supported between instances of 'str' and 'int'
Right
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")Mixing tabs and spaces
Wrong
if number > 5:
print("A") # 4 spaces
print("B") # a tabTabError: inconsistent use of tabs and spaces in indentation
Right
if number > 5:
print("A") # 4 spaces
print("B") # 4 spaces9Solved problems (easy to medium-hard)
All of these are tested. Each shows the problem, the code, the output, and why it works. Press Edit and run on each one and try the values suggested under it.
9.1Level 1: Easy
Problem 1: Voting eligibility
A person can vote if they are 18 or older.
age = 17
if age >= 18:
print("You can vote.")
else:
print("You are too young to vote.")Output
You are too young to vote.
Change it and run: boundary test: set age to 18.
Why: One question, two outcomes. Boundary test: 18 gives "You can vote."
Problem 2: Even or odd
Tell whether a number is even or odd.
number = 7
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")Output
7 is odd
Change it and run: try 10, then 0.
Why: % gives the remainder after division. An even number has remainder 0 when divided by 2.
Problem 3: Positive, negative, or zero
number = -3
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")Output
Negative
Change it and run: try 5, then 0.
Why: Three outcomes need elif. Test values: 5 gives Positive, 0 gives Zero.
Problem 4: Pass or fail
A student passes with 50 or more.
score = 45
if score >= 50:
print("Pass")
else:
print("Fail")Output
Fail
Change it and run: test the boundary: 49, 50 and 51.
Problem 5: Largest of three numbers
a = 12
b = 45
c = 30
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Largest:", largest)Output
Largest: 45
Change it and run: move the largest value to a, then make all three equal.
Why: a is the largest only if it beats both others (and). If not, check b. If neither, it must be c.
9.2Level 2: Medium
Problem 6: Grade calculator
90+ is A, 80-89 is B, 70-79 is C, 60-69 is D, below 60 is F. Scores outside 0-100 are invalid.
score = 83
if score < 0 or score > 100:
print("Invalid score")
elif score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
elif score >= 60:
print("Grade D")
else:
print("Grade F")Output
Grade B
Change it and run: try 95, 59 and 105, then the edges 90, 89 and 60.
Why: The invalid check comes first. Then the grades go from highest to lowest, so we only need >=. Test values: 95 gives A, 59 gives F, 105 gives Invalid.
Problem 7: Cinema ticket price
Rules: under 5 is free. Ages 5 to 17 pay 6. Ages 18 to 64 pay 12, but students pay 8. Ages 65 and over pay 7. A negative age is invalid.
age = 20
is_student = True
if age < 0:
print("Invalid age")
else:
if age < 5:
price = 0
elif age < 18:
price = 6
elif age < 65:
if is_student:
price = 8
else:
price = 12
else:
price = 7
print("Ticket price:", price)Output
Ticket price: 8
Change it and run: try the ages 3, 12, 70 and -1, then age 30 with is_student = False.
Why: It combines elif with a nested if for the student discount. Other tests: age 3 gives 0, age 12 gives 6, age 30 (not student) gives 12, age 70 gives 7, age -1 gives Invalid.
Problem 8: Number guessing hint
The secret number is 42. Say "Correct", "Very close" (within 5), "Too high", or "Too low".
secret = 42
guess = 40
difference = abs(secret - guess)
if guess == secret:
print("Correct!")
elif difference <= 5:
if guess < secret:
print("Very close, a little higher!")
else:
print("Very close, a little lower!")
elif guess < secret:
print("Too low")
else:
print("Too high")Output
Very close, a little higher!
Change it and run: try the guesses 42, 45, 50 and 20.
Why: abs() turns the gap into a positive number, so one check covers both sides. Other tests: 42 gives Correct, 50 gives Too high, 20 gives Too low.
Problem 9: Fizz, Buzz, FizzBuzz
If the number is divisible by 3 print "Fizz", by 5 print "Buzz", by both print "FizzBuzz", otherwise print the number.
number = 15
if number % 15 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)Output
FizzBuzz
Change it and run: try 9, 10 and 7.
Why: The "both" case must come first. Otherwise 15 would be caught by the "divisible by 3" check and print only "Fizz". Tests: 9 gives Fizz, 10 gives Buzz, 7 gives 7.
Problem 10: Simple calculator
Take two numbers and an operator (+, -, *, /). Don't allow division by zero.
a = 10
b = 0
op = "/"
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
if b == 0:
print("Error: cannot divide by zero")
else:
print(a / b)
else:
print("Unknown operator")Output
Error: cannot divide by zero
Change it and run: set b to 4, then set op to "%".
Why: The operator is text, so we compare it with ==. Division has a nested check, because dividing by zero would crash the program. Tests: 10, 4, "/" gives 2.5, and "%" gives Unknown operator.
Problem 11: Login check
The correct username is admin (any capitalization allowed) and the password is secret123 (exact).
username = "Admin"
password = "wrong"
if username.lower() != "admin":
print("Unknown user")
elif password != "secret123":
print("Wrong password")
else:
print("Welcome, admin!")Output
Wrong password
Change it and run: set the password to "secret123", then the username to "guest".
Why: .lower() makes the username check ignore capital letters, but passwords stay case-sensitive. Each failure gets its own helpful message.
Problem 12: BMI category
BMI = weight (kg) divided by height (m) squared. Under 18.5 is Underweight, under 25 is Normal, under 30 is Overweight, otherwise Obese.
weight = 70
height = 1.75
bmi = round(weight / (height ** 2), 1)
print("BMI:", bmi)
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Normal")
elif bmi < 30:
print("Overweight")
else:
print("Obese")Output
BMI: 22.9 Normal
Change it and run: try a weight of 95, then 50 with a height of 1.80.
Why: Because we go from the lowest limit upward, each elif already knows the earlier ones failed, so we only need one < check per line. round(x, 1) keeps one decimal place.
Problem 13: Leap year
A year is a leap year if it is divisible by 4, except century years (like 1900), which must be divisible by 400.
year = 2024
if year % 400 == 0:
print("Leap year")
elif year % 100 == 0:
print("Not a leap year")
elif year % 4 == 0:
print("Leap year")
else:
print("Not a leap year")Output
Leap year
Change it and run: try 2000, 1900 and 2023.
Shorter version with logical operators:
year = 2024
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")Output
Leap year
Why: Tests: 2000 gives Leap, 1900 gives Not leap, 2023 gives Not leap. The order of checks matters: strictest rule first.
Problem 14: Triangle checker
Three sides make a triangle only if each pair of sides adds up to more than the third. Then classify: equilateral (all equal), isosceles (two equal), scalene (none equal).
a = 5
b = 5
c = 8
if a + b > c and a + c > b and b + c > a:
if a == b and b == c:
print("Equilateral triangle")
elif a == b or b == c or a == c:
print("Isosceles triangle")
else:
print("Scalene triangle")
else:
print("Not a triangle")Output
Isosceles triangle
Change it and run: try the sides 3, 3, 3, then 3, 4, 5, then 1, 2, 5.
Why: First question: is it a triangle at all? Only then do we ask which type (nested if). Tests: 3, 3, 3 gives Equilateral, 3, 4, 5 gives Scalene, 1, 2, 5 gives Not a triangle.
9.3Level 3: Medium-Hard
Problem 15: Rock, Paper, Scissors judge
Decide the winner between two players. Rock beats scissors, scissors beats paper, paper beats rock. Ignore capital letters and reject invalid choices.
p1 = "Rock"
p2 = "scissors"
p1 = p1.lower()
p2 = p2.lower()
if (p1 != "rock" and p1 != "paper" and p1 != "scissors") or \
(p2 != "rock" and p2 != "paper" and p2 != "scissors"):
print("Invalid choice")
elif p1 == p2:
print("It's a tie!")
elif (p1 == "rock" and p2 == "scissors") or \
(p1 == "scissors" and p2 == "paper") or \
(p1 == "paper" and p2 == "rock"):
print("Player 1 wins!")
else:
print("Player 2 wins!")Output
Player 1 wins!
Change it and run: try "rock" against "lizard", then "Paper" against "paper".
Why: We clean the input, validate it, check for a tie, then list the three ways Player 1 can win. If none of them is true, Player 2 must have won. The \ at the end of a line lets a long condition continue on the next line. Tests: rock, lizard gives Invalid, Paper, paper gives a tie.
Problem 16: Quadratic equation solver
For ax² + bx + c = 0, the discriminant is d = b² - 4ac. If d > 0 there are two real solutions, if d = 0 there is one, and if d < 0 there are none.
a = 1
b = -3
c = 2
if a == 0:
print("Not a quadratic equation")
else:
d = b ** 2 - 4 * a * c
if d > 0:
x1 = (-b + d ** 0.5) / (2 * a)
x2 = (-b - d ** 0.5) / (2 * a)
print("Two roots:", x1, "and", x2)
elif d == 0:
print("One root:", -b / (2 * a))
else:
print("No real roots")Output
Two roots: 2.0 and 1.0
Change it and run: try a, b, c = 1, 2, 1, then 1, 0, 1, then set a to 0.
Why: We first guard against a = 0 (which would cause division by zero), then use the discriminant to choose the case. d ** 0.5 is the square root. Tests: 1, 2, 1 gives One root: -1.0, 1, 0, 1 gives No real roots.
Problem 17: Date validator
Check whether a given day/month/year is a real date. Remember that February has 29 days only in leap years.
day = 29
month = 2
year = 2023
if month < 1 or month > 12 or day < 1:
print("Invalid date")
else:
if month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
max_day = 29
else:
max_day = 28
elif month == 4 or month == 6 or month == 9 or month == 11:
max_day = 30
else:
max_day = 31
if day <= max_day:
print("Valid date")
else:
print("Invalid date")Output
Invalid date
Change it and run: try 29/2/2024, 31/4/2025, 31/12/2025 and 15/13/2025.
Why: Step 1: reject impossible months and days. Step 2: work out the maximum number of days for that month (using the leap-year rule for February). Step 3: compare the day with that maximum. Tests: 29, 2, 2024 is Valid, 31, 4, 2025 is Invalid, 31, 12, 2025 is Valid, 15, 13, 2025 is Invalid.
Problem 18: Online shop total
Rules: Subtotal of 200 or more gets a 15% discount. 100 or more gets 10%. Below 100 gets none. Members get an extra 5% on top. Shipping is free if the amount after the discount is 75 or more. Otherwise shipping is 6.99.
subtotal = 120
is_member = True
if subtotal >= 200:
discount_percent = 15
elif subtotal >= 100:
discount_percent = 10
else:
discount_percent = 0
if is_member:
discount_percent = discount_percent + 5
discount = subtotal * discount_percent / 100
after_discount = subtotal - discount
if after_discount >= 75:
shipping = 0
else:
shipping = 6.99
total = after_discount + shipping
print("Discount percent:", discount_percent)
print("Shipping:", shipping)
print("Total:", round(total, 2))Output
Discount percent: 15 Shipping: 0 Total: 102.0
Change it and run: try a subtotal of 50 (member), then 250 with is_member = False.
Why: Real programs often use several separate decisions in sequence, where each result feeds the next one. Tests: subtotal 50, member gives total 54.49 (with shipping), and subtotal 250, non-member gives total 212.5.
10Practice problems (try them yourself)
Fifteen problems in three levels. Open the editor under a problem, write your code and press Run to try it with the value in the input box. Then press Check: the page runs your code with several inputs, including the boundary values, and shows for each one whether your output is the expected one. Print exactly the text the problem asks for.
Easy
One decision each.
- 1.Ask for a number and print whether it is greater than 100 or not:
Greater than 100orNot greater than 100.Examples:150givesGreater than 100100givesNot greater than 10099givesNot greater than 100Show a hint
Two outcomes, soif/else. Is exactly 100 greater than 100?Show one possible solution
Pythonnumber = int(input()) if number > 100: print("Greater than 100") else: print("Not greater than 100")Output
Greater than 100
- 2.Check whether a number is divisible by 5. Print
Divisible by 5orNot divisible by 5.Examples:25givesDivisible by 57givesNot divisible by 50givesDivisible by 5Show a hint
A number is divisible by 5 when the remaindernumber % 5is 0.Show one possible solution
Pythonnumber = int(input()) if number % 5 == 0: print("Divisible by 5") else: print("Not divisible by 5")Output
Divisible by 5
- 3.Check whether a person is a teenager (13 to 19 years old). Print
TeenagerorNot a teenager.Examples:16givesTeenager13givesTeenager19givesTeenagerShow a hint
A range check:13 <= age <= 19. Test 12, 13, 19 and 20.Show one possible solution
Pythonage = int(input()) if 13 <= age <= 19: print("Teenager") else: print("Not a teenager")Output
Teenager
- 4.Print the smaller of two numbers.Examples:
3, 8gives38, 3gives35, 5gives5Show a hint
Comparea < b. If the two numbers are equal, either one is the right answer.Show one possible solution
Pythona = int(input()) b = int(input()) if a < b: print(a) else: print(b)Output
3
- 5.A museum ticket costs 20. Children under 12 pay 10, and visitors aged 65 or more pay 15. Read the age and print the price like
Price: 20.Examples:8givesPrice: 1011givesPrice: 1012givesPrice: 20Show a hint
Three outcomes:if,elif,else. Store the price in a variable and print it once at the end. Test 11, 12, 64 and 65.Show one possible solution
Pythonage = int(input()) if age < 12: price = 10 elif age >= 65: price = 15 else: price = 20 print("Price:", price)Output
Price: 10
Medium
Chains, ranges and combined conditions.
- 6.Print the season from a month number (12, 1, 2 is
Winter, 3 to 5 isSpring, 6 to 8 isSummer, 9 to 11 isAutumn). Print an error for other numbers:Invalid month.Examples:1givesWinter4givesSpring7givesSummerShow a hint
Check the invalid numbers first. Winter needsor, because 12 is not next to 1 and 2.Show one possible solution
Pythonmonth = int(input()) if month < 1 or month > 12: print("Invalid month") elif month == 12 or month <= 2: print("Winter") elif month <= 5: print("Spring") elif month <= 8: print("Summer") else: print("Autumn")Output
Winter
- 7.Convert a time (hour from 0 to 23) into
Good morning,Good afternoon,Good evening, orGood night: 5 to 11 is morning, 12 to 17 is afternoon, 18 to 21 is evening, and every other hour is night.Examples:9givesGood morning5givesGood morning11givesGood morningShow a hint
Night is split in two (22 to 23 and 0 to 4), so letelsecatch it. Use chained comparisons like5 <= hour <= 11.Show one possible solution
Pythonhour = int(input()) if 5 <= hour <= 11: print("Good morning") elif 12 <= hour <= 17: print("Good afternoon") elif 18 <= hour <= 21: print("Good evening") else: print("Good night")Output
Good morning
- 8.Water state: at or below 0 °C is
Ice, between 0 and 100 isLiquid, at or above 100 isSteam. The temperature can be a decimal number.Examples:25givesLiquid0givesIce-5givesIceShow a hint
Read the value withfloat(input()). Go from the lowest limit upward:<= 0, then< 100, thenelse.Show one possible solution
Pythontemperature = float(input()) if temperature <= 0: print("Ice") elif temperature < 100: print("Liquid") else: print("Steam")Output
Liquid
- 9.A password is accepted only if it equals
"python123"or equals"admin2026". PrintAccess grantedorAccess denied.Examples:python123givesAccess grantedadmin2026givesAccess grantedPython123givesAccess deniedShow a hint
The password is text, so no conversion. Repeat the full comparison on both sides ofor. Passwords are case-sensitive.Show one possible solution
Pythonpassword = input() if password == "python123" or password == "admin2026": print("Access granted") else: print("Access denied")Output
Access granted
- 10.Taxi fare: a base fare of 3, plus 1.5 per km for the first 10 km and 1.2 per km after that. Add a night surcharge of 2 if the hour is 22 or later or before 6. Read the distance and the hour, and print the fare like
Fare: 10.5.Examples:5, 14givesFare: 10.510, 14givesFare: 18.015, 14givesFare: 24.0Show a hint
Two separate decisions in sequence. First the distance: for more than 10 km the price is10 * 1.5 + (km - 10) * 1.2. Then the night check withor.Show one possible solution
Pythonkm = float(input()) hour = int(input()) fare = 3 if km <= 10: fare = fare + km * 1.5 else: fare = fare + 10 * 1.5 + (km - 10) * 1.2 if hour >= 22 or hour < 6: fare = fare + 2 print("Fare:", round(fare, 2))Output
Fare: 10.5
- 11.Exam result: a student passes with a score of at least 50 and an attendance of at least 75 (percent). Read the score and the attendance. Print
Pass with distinctionfor a pass with a score of 90 or more,Passfor other passes, and for a fail say why:Fail: low score,Fail: low attendance, orFail: low score and low attendance.Examples:70, 90givesPass95, 80givesPass with distinctionShow a hint
First decide pass or fail withand. Inside the pass block, ask the second question about 90. For the fails, check the "both" case first.Show one possible solution
Pythonscore = int(input()) attendance = int(input()) if score >= 50 and attendance >= 75: if score >= 90: print("Pass with distinction") else: print("Pass") elif score < 50 and attendance < 75: print("Fail: low score and low attendance") elif score < 50: print("Fail: low score") else: print("Fail: low attendance")Output
Pass
Medium-Hard
Several decisions together.
- 12.Given three numbers, print them in order from smallest to largest using only
if/elif/else, on one line like1 2 3.Examples:3, 1, 2gives1 2 31, 2, 3gives1 2 3Show a hint
Find the smallest first (it must be<=both others). Then one more comparison puts the other two in order.print(a, b, c)prints three values on one line.Show one possible solution
Pythona = int(input()) b = int(input()) c = int(input()) if a <= b and a <= c: if b <= c: print(a, b, c) else: print(a, c, b) elif b <= a and b <= c: if a <= c: print(b, a, c) else: print(b, c, a) else: if a <= b: print(c, a, b) else: print(c, b, a)Output
1 2 3
- 13.Given a year, print the number of days in the year (
365or366).Examples:2024gives3662023gives3651900gives365Show a hint
Reuse the leap-year rule from solved problem 13. Test the century years 1900 and 2000.Show one possible solution
Pythonyear = int(input()) if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print(366) else: print(365)Output
366
- 14.Check whether three numbers could be the sides of a right-angled triangle (use a² + b² = c² with the longest side as c). Print
Right-angledorNot right-angled.Examples:3, 4, 5givesRight-angled5, 3, 4givesRight-angledShow a hint
The longest side is not always the third number. First find it (like solved problem 5), then compare the squares with**and==.Show one possible solution
Pythona = int(input()) b = int(input()) c = int(input()) # find the longest side first if a >= b and a >= c: longest = a x = b y = c elif b >= a and b >= c: longest = b x = a y = c else: longest = c x = a y = b if x ** 2 + y ** 2 == longest ** 2: print("Right-angled") else: print("Not right-angled")Output
Right-angled
- 15.A phone-plan advisor: given monthly minutes and monthly gigabytes used, recommend
Basic,Standard, orPremiumusing your own rules. Write your rules down as comments first.Show a hint
Decide the limits for Premium first (the strictest rule), then Standard, and letelsebe Basic. Should a plan need many minutesandmany gigabytes, or is one of them enough (or)?Show one possible solution
Pythonminutes = 320 gigabytes = 12 if minutes > 1000 or gigabytes > 20: plan = "Premium" elif minutes > 300 or gigabytes > 5: plan = "Standard" else: plan = "Basic" print("Recommended plan:", plan)Output
Recommended plan: Standard
11Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
12Quick summary
| Concept | What it does | Example |
|---|---|---|
if | Runs a block only when the condition is True | if age >= 18: |
else | Runs when the if condition is False | else: |
elif | Checks another condition (only one block in the chain runs) | elif score >= 80: |
| Condition | A question with a True/False answer | x > 5 |
| Indentation | 4 spaces; shows which lines belong to the block | print("Hi") |
Nested if | An if inside another if | second question after the first |
and / or / not | Combine or flip conditions | a > 1 and b < 5 |
| Chained comparison | Range check | 10 <= x < 20 |
| Truthy/falsy | Non-boolean values used as conditions | 0 and "" are False |
| One-line if/else | Short decision in one line | "adult" if age >= 18 else "minor" |
pass | Empty placeholder block | pass |