South Plantation High School logo
South Plantation High School · Procedural Programming with Python

Conditional Statements in Python

if · if-else · if-elif-else · Lesson review

Review the lesson slides, then complete the assignment at the bottom of this page. Your assignment work is saved in this browser on this computer. When you check a task, your name, period, and which tasks are complete are shared with your teacher (your code is not). When you finish, print it or save it as a PDF to turn in.
1 / 16
Lesson Review

Conditional Statements

ifif-elseif-elif-else

Teaching your program to make decisions.

By the end of this lesson you will be able to:

  • Write conditions that Python answers with True or False.
  • Use if to run code only when a condition is True.
  • Use if-else to choose between two paths.
  • Use if-elif-else to choose between many paths.
  • Spot and fix the most common mistakes and error messages.
How to use this page: Use the Next and Back buttons (or the arrow keys). When you see a TRY IT editor, change the values and click ▶ Run to watch which lines Python runs.

Words you will hear today

WordWhat it meansExample
conditionAn expression that Python answers with True or Falsescore >= 70
BooleanThe type of True and False (bool)True
comparison operatorA symbol that compares two values==, <, !=
logical operatorA word that combines conditionsand, or, not
branchOne of the possible paths a program can takethe if body or the else body
bodyThe indented lines that run when a branch is chosen print("Pass")
  • Conditionals let a program choose what to do.
  • Every condition becomes either True or False.
  • Condition, Boolean, comparison, logical operator, branch, body.

Today we are going to teach our programs how to make decisions. So far, every program we wrote ran every line, top to bottom, every time. After today, your programs will be able to look at a value and decide which lines to run. Watch for the Try It editors, because you will get to test this yourself.

The Big Idea

Programs that make decisions

You make decisions all day based on conditions:

  • If it is raining, take an umbrella. Otherwise, wear sunglasses.
  • If your phone battery is below 20%, plug it in.

Programs do the same thing:

  • A game: if health reaches 0, show "Game Over."
  • A login page: if the password is correct, open the account. Else, show an error.
  • A grade book: if the score is 90 or more, give an A, else if it is 80 or more, give a B...
A condition is a yes or no question. In Python, the answer is always True or False. A conditional statement uses that answer to decide which code runs.
Flowchart of a decision Start, then the question Is it raining. If True, take an umbrella. If False, wear sunglasses. Both paths then go to school. Start Is it raining? True False Take umbrella Wear sunglasses Go to school

Only one of the two orange boxes happens. Then the program continues.

Why programs need decisions

Without conditionals, a program does exactly the same thing every time, no matter what the user types or what happens in the game. Conditionals let one program react differently to different situations. Almost every real program is full of them.

Turning an everyday rule into code

"If your phone battery is below 20%, plug it in" becomes:

if battery < 20:
    print("Plug in your phone.")

The condition is the part after if (battery < 20). The action is the indented line. Practice by turning rules you know (school, games, sports) into this shape.

  • A condition is a question with a True or False answer.
  • A flowchart diamond shows a decision point.
  • After the decision, the program keeps going.
  • Conditionals let one program react to different situations.

Look at the flowchart. The diamond is the decision. Python asks the question, gets True or False, and follows only one arrow. Notice that both paths come back together at the end. That is exactly how an if-else statement works in code. Can someone give me another example of a decision an app makes?

Building Conditions

Comparison operators: True or False?

A comparison checks two values and gives back a Boolean value: True or False.

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 3True
>greater than7 > 10False
<less than3 < 8True
>=greater than or equal to10 >= 10True
<=less than or equal to4 <= 2False
Watch out: = stores a value in a variable. == compares two values. In a condition you almost always want ==.

Comparison playground

Pick two numbers and an operator. Python prints the result of the comparison.

compare.pyTRY IT
TerminalOutput

Comparing more than numbers

  • Strings can be compared too. == checks if they are exactly the same, letter for letter and capital for capital: "cat" == "Cat" is False.
  • < and > on strings compare in dictionary order: "apple" < "banana" is True. Careful: all capital letters come before all lowercase ones, so "Zebra" < "apple" is also True.
  • An int and a float with the same value are equal: 5 == 5.0 is True.

You can store the answer

A comparison is an expression, so its True/False result can be saved: is_adult = age >= 18. Later, if is_adult: reads almost like English.

Reading the symbols: say >= as "is at least" and <= as "is at most." The = always comes second: => is a SyntaxError.

  • Comparisons always produce True or False (capital T and F).
  • >= includes the equal case. 10 >= 10 is True, but 10 > 10 is False.
  • = assigns, == compares.
  • String comparisons are case sensitive.
  • You can store a comparison: is_adult = age >= 18.

Every condition we write is built from comparisons like these. Try the playground with 10 and 10. Switch between greater than and greater than or equal to. Notice how one includes the equal case and the other does not. This tiny difference causes a lot of bugs, so read every operator carefully.

Building Conditions

Combining conditions: and, or, not

OperatorThe result is True when...ExampleResult
andboth sides are True5 > 3 and 2 > 9False
orat least one side is True5 > 3 or 2 > 9True
notthe condition is False (it flips the answer)not 5 > 3False
Tip: Write the full comparison on both sides. age > 12 and age < 20 is correct. age > 12 and < 20 is a SyntaxError.

Python also lets you chain comparisons: 13 <= age <= 19 means the same thing as age >= 13 and age <= 19.

A movie theater lets you in only if you are 13 or older and you have a ticket. Change the values and run it.

Truth tables: every possible case

ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

Memory trick: and is picky (everything must be True). or is easygoing (one True is enough).

Order of operations: not goes first, then and, then or. Comparisons like > happen before all three. When you mix and and or, add parentheses so the meaning is clear: (is_weekend or is_holiday) and not raining.

  • and: both must be True.
  • or: one is enough.
  • not: flips True to False and False to True.
  • and is picky; or is easygoing.
  • Order: comparisons, not, and, or.

Sometimes one question is not enough. A theater might need two things to be true at the same time, so we use and. Try age 15 with no ticket, then age 10 with a ticket. Both get denied. Only when both conditions are True do you get in. What would change if we used or instead?

Part 1 · if

Anatomy of an if statement

ifkeyword
temperature > 85condition
:colon
····4 spaces
print("Stay hydrated!")indented body
  • Keyword: if is always lowercase.
  • Condition: any expression that is True or False.
  • Colon: the : at the end says "the code block starts on the next line."
  • Body: the indented lines underneath. Python runs them only when the condition is True. If it is False, Python skips them.

The body can have more than one line. Every line in the body must be indented the same amount.

temperature = 92
if temperature > 85:
    print("It is hot outside.")
    print("Stay hydrated!")
print("Enjoy your day.")
It is hot outside. Stay hydrated! Enjoy your day.

How Python reads it

  1. Python reaches the if line and evaluates the condition: 92 > 85 becomes True.
  2. Because it is True, Python goes into the body and runs each indented line in order.
  3. When it reaches a line that is back at the left edge, the body is over. Python continues from there.

If the condition had been False, Python would have jumped straight from the if line to print("Enjoy your day.").

The colon is easy to forget. Think of it as saying "here comes the block." Every if, elif, and else line ends with one.

  • Four parts: if, condition, colon, indented body.
  • The body runs only when the condition is True.
  • Unindented lines after the body always run.
  • True: run the body. False: jump past it.

Every if statement has the same four parts. Point to each one on your screen with me: the keyword if, the condition, the colon, and the indented body. The colon and the indentation are the two things students forget most often, and Python will not run your program without them.

Part 1 · if

Try it: if in action

Change the temperature and click ▶ Run. Watch which lines turn green (Python ran them) and which fade out (Python skipped them).

ranskipped
Try these: 92, then 70, then exactly 85. Why does 85 not print the hot message? (Hint: look at the operator.) Notice that line 4 runs every time because it is not indented. It is not part of the if body.

Edge values: test the boundary

The number right at the dividing line (here, 85) is called an edge value or boundary. Bugs love to hide there, because > and >= only disagree at that one number.

  • 85 > 85 is False (85 is not greater than itself).
  • 85 >= 85 is True.

So ask yourself: "Should exactly 85 count as hot?" Then pick the operator that matches. When you test any condition, try a value below, a value above, and the value exactly on the line.

  • An if by itself either runs its body or does nothing.
  • 85 > 85 is False.
  • Code after the body always runs.
  • Test below, above, and exactly on the boundary.

Run it with 92 first. Line 3 runs. Now try 70. Line 3 is skipped, but line 4 still runs. Now try 85. Who can explain why the hot message did not print? Right, 85 is not greater than 85. If we wanted 85 to count, what operator would we use?

Part 1 · if

Indentation decides what is inside

In Python, indentation is not just for looks. The spaces at the start of a line tell Python which lines belong to the if statement. The standard is 4 spaces. (In most Python editors, pressing Tab inserts 4 spaces for you.)

Example A: both prints are inside
score = 50
if score >= 70:
    print("You passed!")
    print("Great job!")
(nothing prints)
Example B: only one print is inside
score = 50
if score >= 70:
    print("You passed!")
print("Great job!")
Great job!

The code is almost the same, but the result is different. In Example B, print("Great job!") is not indented, so it is outside the if and always runs.

Indentation errors you may see

ProblemError message
The line after if ...: is not indentedIndentationError: expected an indented block after 'if' statement on line 2
A line has extra spaces that do not match the lines around itIndentationError: unexpected indent

How to tell where a block ends

A block ends at the first line that is indented less than the block. Blank lines in between do not end it. That is why the colon and the indentation work together: the colon says "a block starts," and going back to the left says "the block is done."

No error is not the same as correct. In Example B, Python happily runs the program. It just does something different from Example A. When the output is surprising, check the indentation of each line first.
  • Indented lines belong to the if.
  • Use 4 spaces and be consistent.
  • The block ends when a line goes back to the left edge.
  • A block ends at the first line indented less than it.

Compare Example A and Example B. The only difference is four spaces in front of the last line. In A, both lines are inside the if, so nothing prints. In B, the last line is outside the if, so it always prints. In Python, spaces change what your program does.

Part 2 · if-else

Two paths: if-else

Use else when you want something to happen when the condition is False.

if condition:
    # runs when the condition is True
else:
    # runs when the condition is False
  • else has no condition. It catches everything the if did not.
  • else needs its own colon : and its own indented body.
  • else lines up with its if (same indentation).
  • Exactly one of the two bodies runs. Never both, never neither.
ranskipped

Try 85, 70, and 69. What is the smallest score that passes?

Why else has no condition

else means "in every other case." Its condition is already decided: it is simply "the if was False." Writing else score < 70: is a SyntaxError because the condition would be redundant.

Use the opposite carefully

The opposite of score >= 70 is score < 70, not score <= 70. With else, you never have to work out the opposite yourself, which removes a common source of bugs.

  • if-else always runs exactly one of its two bodies.
  • else never has a condition.
  • Line up else with if.
  • else means "every other case"; it never needs a condition.

With just an if, the program either does something or does nothing. With if-else, the program always does one of two things. Think of a fork in the road: you must go left or right, and you cannot go both ways. Run it with 70 and 69 and tell me what you see.

Part 3 · if-elif-else

Many paths: if-elif-else

elif is short for "else if." Use it when there are more than two choices.

if condition1:
    # runs if condition1 is True
elif condition2:
    # runs if condition1 is False and condition2 is True
else:
    # runs if all conditions above are False
  • Python checks the conditions from top to bottom.
  • The first condition that is True wins. Its body runs, and Python skips the rest of the chain.
  • You can use as many elif lines as you need.
  • The else at the end is optional. If there is one, it must be last.
ranskipped
Try 85: Python checks 85 >= 90 (False), then 85 >= 80 (True). It sets the grade to "B" and never even looks at the other conditions. Then try 95, 72, 60, and 30.

Why elif score >= 80 is enough for a B

You might think the B condition should be score >= 80 and score < 90. It does not need the second part! Python only reaches the elif if the if above it was False, which already means the score is below 90. Each elif quietly includes "and everything above me was False."

Trace for a score of 72

CheckResultWhat Python does
72 >= 90Falsemove to the next check
72 >= 80Falsemove to the next check
72 >= 70Truerun this body, then skip the rest
  • elif means "else if."
  • Top to bottom, first True wins, the rest are skipped.
  • At most one body in the chain runs (exactly one if there is an else).
  • Each elif already knows that every condition above it was False.

This is the grade book example. Watch the badges next to each condition when you run it. Python asks the first question. If the answer is no, it moves down and asks the next one. As soon as it gets a yes, it runs that body and jumps out of the whole chain. The badges that say skipped were never even checked.

Part 3 · if-elif-else

Order matters!

This program has a logic error. It runs without crashing, but it gives the wrong answer. Run it with a score of 95.

What went wrong? 95 >= 60 is True, so the very first condition wins and the student gets a D. Python never reaches the A check. With this order, nobody can ever get an A, B, or C.
How to fix it: put the most specific (hardest to reach) condition first. For grades, check from the highest score down: 90, then 80, then 70, then 60, like the program on the previous slide.

A rule for ordering conditions

When conditions overlap (a score of 95 is also at least 60, 70, and 80), the one that is hardest to meet must go first. Think of it as sorting candidates from most exclusive to least.

  • Checking with >=? Start from the biggest number and go down.
  • Checking with <? Start from the smallest number and go up: if score < 60: "F", elif score < 70: "D", and so on.

Both orders work, as long as you stay consistent within one chain.

  • A logic error runs without an error message but gives the wrong result.
  • In an elif chain, put the most specific condition first.
  • Always test with several values, including edge values like 90 and 89.
  • Most exclusive condition first: >= from high to low, < from low to high.

This is one of the sneakiest bugs in programming. Python does not give you an error message. It just quietly gives the wrong answer. Run it with 95 and watch: the first condition is True, so Python stops right there. This is why we test our programs with many different values, not just one.

Part 3 · if-elif-else

elif vs. separate if statements

Each separate if is its own decision, so Python checks every one. An elif chain is one decision, so Python stops at the first True. Run both with the same score and compare the output.

Separate ifs: every one is checked
One if-elif chain: stops at the first True
Rule of thumb: if only one of the choices should happen, use if-elif-else. If each check is a separate question that could also be True (like "Is it Friday?" and "Is it raining?"), use separate if statements.

What you see when you run both with 95

With separate ifs, a score of 95 passes the A check, then also the B and C checks, so A, B, and C all print. With one chain, Python prints only the A and skips the rest.

A test to decide which to use

Ask: "Could more than one of these be true, and should all of those actions happen?"

  • Yes: use separate ifs. Example: give a bonus if the player found a key, and also if they beat the clock.
  • No, pick only one: use if-elif-else. Example: a letter grade, a ticket price by age group.
  • Separate ifs: each is checked, so more than one body can run.
  • elif chain: only the first True body runs.
  • Several might apply and all should happen: separate ifs. Pick one: elif chain.

Run both editors with 95. The left side prints three messages because each if is checked on its own, and 95 is greater than 90, 80, and 70. The right side prints only one because the chain stops after the first True. Neither is wrong. You just need to pick the one that matches what you want to happen.

Real Programs

Conditionals with input()

input() always gives back a string (text), even if the user types a number. To compare it with a number, convert it first:

  • int() converts to a whole number.
  • float() converts to a decimal number.
Without int()
age = input("Age: ")     # age is "15", a string
if age > 13:
    print("Teen")
TypeError: '>' not supported between instances of 'str' and 'int'
With int()
age = int(input("Age: "))   # age is 15, a number
if age > 13:
    print("Teen")
Sneaky one: "5" == 5 does not crash. It is just False, because text and a number are never equal. Also, string comparisons are case sensitive: "Yes" == "yes" is False. You can use answer.lower() == "yes" to accept any capitalization.

Type a whole number into the box (this is what the user types at the prompt) and click Run. Then try typing a word like ten to see what happens when int() gets text it cannot convert.

What int(input("Age: ")) does, from the inside out

  1. input("Age: ") shows the prompt and waits. The user types 15 and presses Enter. The result is the string "15".
  2. int("15") turns that text into the number 15.
  3. age = 15 stores the number, so age > 13 can now compare numbers.

When the user types something that is not a number, like ten or 15.5, int() fails with ValueError: invalid literal for int() with base 10. Use float() if decimals are allowed.

Accepting yes, Yes, or YES: .lower() makes a lowercase copy of the text, so answer.lower() == "yes" matches all three.

  • input() returns a string.
  • Wrap it in int() or float() before comparing with numbers.
  • String comparisons are case sensitive.
  • int(input()) runs inside out: input gives text, int makes a number.

This is where conditionals get useful, because now the user controls what happens. Remember that input always gives you text. If you forget int, Python will either crash with a TypeError or, with double equals, quietly say False. Try typing a word in the demo and read the ValueError message out loud with me.

Going Further

Nested if statements

You can put an if statement inside another if statement. This is called nesting. The inner if is only checked when the outer condition is True.

has_ticket = True
age = 12

if has_ticket:
    if age >= 13:
        print("Enjoy the PG-13 movie!")
    else:
        print("Please pick a different movie.")
else:
    print("Please buy a ticket first.")
Please pick a different movie.
  • Each level of nesting adds 4 more spaces.
  • Each else belongs to the if it lines up with.
  • Here, has_ticket is True, so Python goes inside. Then 12 >= 13 is False, so the inner else runs.
  • Notice that if has_ticket: works because has_ticket already holds True or False. You do not need to write == True.
Keep it readable: too many levels of nesting gets confusing. Often you can combine conditions with and instead, like if has_ticket and age >= 13:.

Trace all three cases

has_ticketageOutput
True15Enjoy the PG-13 movie!
True12Please pick a different movie.
False(any)Please buy a ticket first. (age is never checked)

When nesting is the better choice

Combining with and is shorter, but nesting is useful when each "no" needs a different message. Here, someone without a ticket and someone who is too young need to hear different things, so the nested version gives clearer feedback.

  • Nested if: an if inside another if's body.
  • Match each else to the if at the same indentation.
  • Use and when it makes the code simpler.
  • Nest when each failed check needs its own message.

Follow the code with your finger. First question: do they have a ticket? Yes, so we go inside. Second question: are they 13 or older? No, so we use the inner else. Indentation shows you which else goes with which if. What would print if has_ticket were False?

Debugging

Common mistakes and their error messages

MistakeWrong codeWhat Python saysFix
Using = instead of ==if x = 5:SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?if x == 5:
Missing colonif x == 5SyntaxError: expected ':'if x == 5:
Body not indentedif x == 5:
print("hi")
IndentationError: expected an indented block after 'if' statement on line 2Indent the body 4 spaces
Putting a condition on elseelse x < 3:SyntaxError: expected ':'else: or elif x < 3:
elif after elseelse: ... then elif x == 2:SyntaxError: invalid syntaxPut every elif before the else
Capital lettersIf x > 5:SyntaxError: invalid syntaxif, elif, else are lowercase
Comparing text to a numberage = input()
if age > 13:
TypeError: '>' not supported between instances of 'str' and 'int'age = int(input())
else without an ifelse: as the first lineSyntaxError: invalid syntaxEvery else needs an if above it

Messages shown are from Python 3.13. Older versions of Python word some of these messages a little differently, but they point to the same mistake. Python also shows the line number and a ^ arrow near the problem.

How to fix errors quickly

  1. Read the last line of the error. SyntaxError and IndentationError mean the code is written wrong; nothing ran. TypeError means it ran until it tried to compare things that cannot be compared.
  2. Go to the line number Python gives. Check for the colon, the double ==, and the indentation.
  3. If that line looks fine, check the line above. A missing parenthesis or quote on one line often gets reported on the next.
Logic errors give no message. A wrong order in an elif chain or > instead of >= runs fine but gives the wrong answer. Catch them by testing several values, especially edge values.
  • Read the last line of the error first. It tells you the type of error.
  • Check the line number Python gives you, and the line just above it.
  • Logic errors give no message: test edge values.

Error messages are clues, not punishments. Read the last line first: it tells you what kind of error you made. Then go to the line number. With conditionals, nine times out of ten the problem is a missing colon, a single equals sign, or indentation.

Practice

Check yourself

Predict what each program does, then click Check. This is practice only. Nothing is graded or recorded.

For each program, trace it:
  • Write down each variable's value.
  • Evaluate each condition to True or False, top to bottom.
  • In an elif chain, stop at the first True. With separate ifs, check every one.
  • Lines that are not indented under anything always run.
  • Trace the code line by line, like the Try It editors do.
  • For elif chains: top to bottom, first True wins.

Take a minute and work these out on your own before you click Check. Trace each program the same way the Try It editors did: which conditions are True, which are False, and which lines run. If you miss one, read the explanation and try to see where your trace went off track.

Summary

Conditional statements cheat sheet

if

if score >= 70:
    print("Pass")

Use when: something should happen only sometimes. Runs the body or does nothing.

if-else

if score >= 70:
    print("Pass")
else:
    print("Retry")

Use when: there are exactly two choices. Exactly one body runs.

if-elif-else

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("Keep going")

Use when: there are three or more choices. First True wins.

Before you run your code, check:

  • Every if, elif, and else line ends with a colon :
  • Every body is indented 4 spaces, and else/elif line up with their if
  • Conditions use == to compare, not =
  • else has no condition, and it comes last
  • In an elif chain, the most specific condition comes first
  • Values from input() are converted with int() or float() before comparing with numbers

Key words to know

condition · Boolean (True/False) · comparison operator · and / or / not · if / elif / else · body · nested if · edge value · logic error

  • if: maybe. if-else: one of two. if-elif-else: one of many.
  • Colon, indentation, double equals, order.
  • Know the key words: condition, Boolean, elif, nested if, edge value, logic error.

Let's review. If means maybe: it runs or it does not. If-else means one of two. If-elif-else means one of many, and the first True wins. Before you run any program with a conditional, go through this checklist. It will save you most of the errors we looked at today.