Making Decisions
Learning Objectives
- You can write comparison expressions that evaluate to
TrueorFalse. - You can write
if,if/else, andif/elif/elsestatements. - You can predict which branch runs for a given input and explain why.
- You can pay deliberate attention to boundary values and branch order.
- You can combine simple boolean expressions using
and,or, andnotwhen one decision depends on more than one condition.
Until now, the programs in this part have mostly followed one straight path. They ask questions, perform calculations, and print results. Real programs often need to behave differently in different situations.
A ticket may cost less for a child. A study session may be classified as short or long. A login message may depend on whether the user entered the expected code.
To make those choices, a program needs expressions that answer yes-or-no questions and a way to use those answers to decide what happens next.
Comparisons Produce Boolean Values
Python has comparison operators for values:
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
Examples:
print(5 > 3)print(5 == 3)print(5 != 3)The output is:
TrueFalseTrueThe result of a comparison is a boolean value.
= and == Are Different
One of the most common beginner mistakes is confusing assignment with equality comparison.
score = 10assigns the value 10 to score.
score == 10asks whether the current value of score equals 10 and produces True or False.
Read them differently:
=means store this value under this name;==means are these two values equal?
Comparing Strings
Strings can be compared for equality too:
answer = "yes"print(answer == "yes")This is case-sensitive:
print("YES" == "yes")is False.
This is why normalizing user input is often useful:
answer = input("Continue? ").strip().lower()print(answer == "yes")Now inputs such as YES, yes, and Yes all become yes before comparison.
The Basic if
A boolean expression becomes especially useful when it controls whether some code runs.
An if statement runs a block of code only when its condition is true.
minutes = 75
if minutes >= 60: print("That was at least an hour.")
print("Session recorded.")The indented line belongs to the if. The final line does not.
If minutes is 75, both messages are printed. If minutes is 30, the first message is skipped and Session recorded. is still printed.
Two syntax details matter:
- the
ifline ends with a colon (:); - the body is indented, normally by four spaces.
You can read the statement almost like ordinary language:
If
minutes >= 60is true, print the message.
Print one conditional message
0 / 10 points
Write a program that reads a whole-number temperature.
If the temperature is below zero, print:
Warning: below freezing.After the conditional, always print:
Temperature checked.Use input() without a visible prompt. A non-negative temperature must therefore produce only the final line.
else for the Alternative
Often there are two mutually exclusive cases:
age = int(input("Age: "))
if age >= 18: print("Adult ticket")else: print("Youth ticket")Exactly one branch runs.
The else does not need its own condition. It means “if the previous condition was false.”
Print one of two outcomes
0 / 10 points
Write a program that reads a whole-number score from 0 through 100.
Print Pass if the score is at least 70. Otherwise, print Not yet.
Use input() without a visible prompt and print only the required message. Pay particular attention to the values 69, 70, and 71.
elif for Several Cases
When there are more than two categories, use elif:
minutes = int(input("Minutes: "))
if minutes < 20: print("Short session.")elif minutes <= 60: print("Solid session.")else: print("Long session.")Python checks the conditions from top to bottom. As soon as one condition is true, that branch runs and the rest are skipped.
If minutes is 45:
45 < 20is false;45 <= 60is true;- the second branch runs;
- the
elseis skipped.
Classify a battery level
0 / 10 points
Write a program that reads a whole-number battery percentage and prints exactly one message:
- below 20:
Low battery - 20 through 79:
Battery okay - 80 or higher:
Battery high
Use an if/elif/else chain and input() without a visible prompt. Test the boundary values 19, 20, 79, and 80 carefully.
Branch Order Matters
Consider this code:
age = 12
if age < 18: print("Minor")elif age < 13: print("Child")The second branch can never run. Anyone younger than 13 is already younger than 18, so the first condition catches them first.
A better order is:
if age < 13: print("Child")elif age < 18: print("Teenager")else: print("Adult")When conditions overlap, the order determines which one wins.
Repair the departure-advice branch order
0 / 10 points
The starter program reads the whole number of minutes until departure and is intended to print exactly one message:
- fewer than 10 minutes:
Leave now. - 10 through 29 minutes:
Get ready. - 30 minutes or more:
Plenty of time.
The narrowest case is currently unreachable because a broader condition appears first. Repair the branch order while keeping an if/elif/else chain. You do not need to combine conditions.
Use input() without a visible prompt and print only the required result.
Boundaries Need Deliberate Attention
Suppose a discount applies to customers aged 65 or older.
The correct comparison is:
age >= 65not:
age > 65The second version wrongly excludes people who are exactly 65.
Boundary values are the values directly at the edge of a rule. They deserve special tests because a single character can change the behavior:
< versus <=> versus >=When you write a classification, ask:
- What happens one step below the boundary?
- What happens exactly at the boundary?
- What happens one step above it?
This is the beginning of a testing habit you will develop more systematically in later parts.
Independent if Statements Are Different
These two programs do not mean the same thing.
Program A:
if score >= 70: print("Passed")
if score >= 90: print("Excellent")Program B:
if score >= 90: print("Excellent")elif score >= 70: print("Passed")If score is 95, Program A prints both messages. Program B prints only Excellent.
Use separate if statements when several independent facts may all be true. Use an if/elif/else chain when you want to select one category from several alternatives.
Combining Conditions
Sometimes one decision depends on more than one yes-or-no question. Boolean expressions can be combined for those situations.
and
and is true only when both sides are true:
age = 20has_ticket = True
if age >= 18 and has_ticket: print("You may enter.")The message is printed only if the person is old enough and has a ticket.
or
or is true when at least one side is true:
is_student = Trueis_senior = False
if is_student or is_senior: print("Discount available.")not
not reverses a boolean value:
is_closed = False
if not is_closed: print("The service is open.")You do not need complicated boolean expressions in Part 1. In fact, complicated expressions are often easier to understand when they are split into named pieces:
old_enough = age >= 18has_permission = answer == "yes"allowed = old_enough and has_permission
if allowed: print("Allowed")Named conditions are often easier to trace and explain.
Build an access condition
0 / 10 points
Write a program that reads two input lines:
- the user’s age as a whole number;
- whether the user agreed to the rules, as
yesorno.
Normalize the agreement text with .strip().lower(). Use these meaningful boolean variables:
old_enough, which is true when the age is at least 16;agreed_to_rules, which is true when the normalized answer isyes;may_access, which combines the other two values usingand.
Print only the value of may_access. Use input() without visible prompts. For the inputs 16 and yes, the output must be:
TrueA Complete Decision Program
Here is a small program that combines input, conversion, arithmetic, string normalization, and conditions:
name = input("Name: ").strip()minutes = int(input("Study minutes today: "))energy = input("Energy level (low/okay/high): ").strip().lower()
hours = minutes / 60
print()print(f"{name}, you studied for {hours:.1f} hours.")
if minutes < 20: print("A short session still counts.")elif minutes <= 90: print("That is a solid block of work.")else: print("That was a long session. Remember to take breaks.")
if energy == "low": print("Consider choosing a lighter next task.")elif energy == "high": print("You may have energy for another focused task.")Notice that the duration classification and the energy message use separate decision structures. They describe different aspects of the session, and both may produce output.
Give weather advice
0 / 15 points
Write a program that reads two input lines:
- a whole-number temperature;
- whether it is raining, as
yesorno.
Normalize the rain answer with .strip().lower(). Use one if/elif/else chain to print exactly one clothing recommendation:
- below 5:
Wear a coat. - 5 through 17:
Wear a jacket. - 18 or higher:
A light layer is enough.
Then use a separate if statement to print Take an umbrella. when the normalized rain answer is yes. This advice is independent of the temperature category.
Use input() without visible prompts and print only the applicable advice lines.
Common Pitfalls
- Writing
=instead of==in a comparison. - Forgetting the colon at the end of
if,elif, orelse. - Using inconsistent indentation.
- Putting a broad condition before a narrower one in an
elifchain. - Forgetting to normalize text before comparing when case and whitespace should not matter.
- Choosing
<when the requirement really says “less than or equal to,” or vice versa. - Assuming that if a program works on one test value, all boundary values must also be correct.
- Combining so many conditions in one expression that the rule becomes hard to explain.
Check Your Understanding
- What type of value does a comparison produce?
- What is the difference between
=and==? - What determines whether the body of an
ifstatement runs? - In an
if/elif/elsechain, how many branches can run? - Why does branch order matter?
- Why should exact boundary values be tested deliberately?
- What is the difference between two separate
ifstatements and aniffollowed byelif? - When might one decision need
andoror?
AI Study Aid
Create a chapter diagram
We're looking into to what extent AI-generated diagrams could help with studying.
Use this study aid to generate an AI-generated visual summary of the material you just studied.
Each diagram style emphasizes the content in a different way, so you can choose the focus
that feels most useful.
Using the diagram generator is voluntary and does not affect your course progress. We encourage
you to try it out and see if it helps, but it's totally up to you! Your answers help us understand
how to make better study aids in the future.