Embercode
✕
ConditionalsLesson 1 of 14

45 min read

if, elif and else in Python

Why it matters

A program that does the same thing every time is a calculator with no judgment. Real software decides. It lets a user log in or keeps them out, gives a discount or does not, and warns about a low battery while staying quiet otherwise. The if statement is the basic tool for making those decisions. Searching, sorting, checking input and dynamic programming all contain an if at their core, so you will use this lesson in every later module.

This lesson starts from nothing. You will write programs that read input, test it and print different answers. You will also meet the traps that catch most beginners: indentation that does not match the meaning, = where == belongs, and tests in the wrong order.

Start with a question that has a yes or no answer

A Python program is a list of instructions. Without decisions, the computer runs them from top to bottom every time. A conditional lets the list branch. The program asks a question, and the answer decides which instructions run next.

The question is called a condition. A condition gives one of two answers, True or False. Python calls this type bool. You already know int for whole numbers and float for decimal numbers. bool is the third basic type you need for decisions. A variable of type bool holds only True or False. The capital letter matters. true written in lower case is an ordinary name, and Python stops with NameError: name 'true' is not defined. Did you mean: 'True'? if you use it as a value.

Think of a bouncer at a club door. The bouncer checks one thing: "Are you on the list?" The answer decides whether you walk in or wait outside. A condition is one of those checks, and the program's answer decides the next step.

Conditions are usually built with a comparison operator. A comparison operator compares two values and produces a bool. Here are the six you need. The examples assume x holds 5.

OperatorMeaningExampleResult
==equal tox == 5True
!=not equal tox != 5False
<less thanx < 5False
<=less than or equal tox <= 5True
>greater thanx > 5False
>=greater than or equal tox >= 5True

Notice the two-character operators. == asks a question. = stores a value in a variable, so x = 5 puts 5 into x, and x == 5 only checks whether x already holds 5. Mixing them up is one of the most common beginner errors. In an if line, Python stops with a syntax error that names the mistake. You will see the exact message later in this lesson.

A bool variable can also be a condition on its own. If you write is_raining = True, then if is_raining: is a complete, valid test. You do not need is_raining == True. That also works, but the short form is the normal style.

The if statement

The shape of an if statement has three parts: the word if, a condition, and a colon at the end of the line.

if condition:
    code that runs only when the condition is true

The lines under the colon, indented by four spaces, form the block. Python uses indentation to mark the block. There are no curly braces, so the spaces at the start of each line are part of the code. A line with no indentation is outside the block.

The computer evaluates the condition. If the answer is True, it runs every line in the block, then continues with the first line that is not indented. If the answer is False, it skips the whole block.

Here is a short example. It does not read any input.

Python · editable
Adult
Checked

The line print("Checked") is not indented, so it runs in both cases. If age were 12, the program would print only Checked.

Next, a program that reads input. input() waits for the user to type a line and press Enter. It always returns text, not a number, so int(...) converts the text into a whole number. Type -4 and press Enter.

number = int(input())
 
if number > 0:
    print("positive")
elif number < 0:
    print("negative")
else:
    print("zero")

With -4 typed in, the output is:

negative

Here is what happens step by step. input() reads the line -4 and gives back the text "-4". int("-4") turns that text into the number -4, and number stores it. The test number > 0 is False, so its block is skipped. The next test, number < 0, is True, so negative prints. Once one branch has run, Python skips the rest of the chain, so the zero line never runs.

The word elif is short for "else if". You will see it in the next section.

The else part

The else block runs when the if condition is False. It is the fallback for the other case. Without else, a false condition does nothing.

Python · editable
Take a coat

An if with an else always runs exactly one of the two blocks. That is useful when every possible answer needs an action. An if without an else is useful when you only want to react in one case, such as printing a warning.

elif ladders

Real decisions often have more than two outcomes. A grade has five letters, a delivery fee has several bands, and a traffic light has three colours. You can chain conditions with elif. Python checks them from the top, runs the first block whose test is True, and skips every other block in the chain.

Think of a set of sieves with holes of decreasing size. The first sieve catches the big pieces, and anything that falls through goes to the next. Each elif is a sieve that catches only what the earlier sieves let through.

Here is a grade program. Type 72 and press Enter. Then try 95, 75, 59 and 100 to check each band.

marks = int(input())
 
if marks >= 90:
    print("Grade: A")
elif marks >= 75:
    print("Grade: B")
elif marks >= 60:
    print("Grade: C")
else:
    print("Grade: Fail")

With 72, the output is:

Grade: C

Trace it. 72 >= 90 is False. 72 >= 75 is False. 72 >= 60 is True, so Grade: C prints. The else does not run.

The order of the tests is not a style choice. It decides the answer. Suppose you wrote the bands from the bottom up, with marks >= 60 first. A score of 95 passes that first test and prints C, which is wrong, because the A test never gets a chance to run. The rule is simple: put the highest cut-off first, then work down. Each test can then assume the earlier tests were False.

When you write a ladder, ask yourself for every test: "What do I already know, because the tests above it were False?" For the marks >= 75 test, you already know that marks is below 90, so the test only has to decide between 75 and 89. This is why the code is short. It does not repeat the upper bound.

Python also lets you write a range check in one line. 10 <= score <= 20 means "score is at least 10 and at most 20". Many languages need two separate tests for this. Python reads the chained form as two tests joined by and, so the one-line version is correct.

Combining conditions with and, or and not

Sometimes one question is not enough. "The user is an adult and has a ticket" is two tests at once. Python combines bool values with three words.

  • and gives True only when both sides are True.
  • or gives True when at least one side is True.
  • not flips a bool: not True is False.

A truth table shows every case. Read each row as "left side, right side, result".

left    right   left and right   left or right
True    True    True             True
True    False   False            True
False   True    False            True
False   False   False            False

Operator precedence decides what groups with what when there is no bracket. Comparisons such as >= bind tightest, then not, then and, then or. Brackets make the intention clear and cost nothing, so use them whenever you mix and and or. For example, a or b and c means a or (b and c), which is often not what a reader expects.

Here is a range check. A value is inside the range from 10 to 20 when it is at least 10 and at most 20:

Python · editable
In range

The chained form if 10 <= score <= 20: gives the same result. Either form is fine. Use the one that reads more clearly to you.

Values that count as True or False

Python's if does not need a bool. It takes any value and asks whether that value counts as true. This is called truthiness. Some values count as False: the number 0, the empty text "", the empty list [], and None, which is Python's word for "no value". Almost everything else counts as True.

Python · editable
None False
0 False
'' False
[] False
'0' True
0.0 False
' ' True

The text "0" counts as True, because it is a non-empty string. The space " " also counts as True. Truthiness is handy for checks such as if items:, which means "the list is not empty". It can also mislead you. A score of 0 is a real score, but if score: treats it as "no score". Write if score is not None: when 0 is a valid value.

Short-circuit evaluation

Python evaluates and and or from left to right and stops as soon as the answer is known. This is called short-circuit evaluation. If the left side of and is False, the whole thing must be False, so Python never evaluates the right side. If the left side of or is True, the right side is skipped.

This matters when the right side could fail. Dividing by zero is the classic example. The next program divides 100 by a number the user types. Type 0 and press Enter.

d = int(input())
 
if d != 0 and 100 / d > 10:
    print(f"100 divided by {d} is more than 10")
else:
    print("Skipped: divisor is 0 or the result is 10 or less")

With 0, the output is:

Skipped: divisor is 0 or the result is 10 or less

When d is 0, the test d != 0 is False. The and already has its answer, so Python never computes 100 / d. If you swap the two tests to 100 / d > 10 and d != 0, the program divides by zero first and stops with this error (the path on the File line shows where your file is saved):

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    if 100 / d > 10 and d != 0:
       ~~~~^~~
ZeroDivisionError: division by zero

Short-circuit evaluation gives you a free guard. Put the cheap or safe test first and the risky test second. Many real bugs are None or empty-list checks written in the wrong order.

A small program: ticket gate

A cinema gate lets a guest in when they are 18 or older and hold a ticket. Under 18, the answer is always "too young". The program reads an age, then reads whether the guest has a ticket.

age = int(input())
has_ticket = input().strip() == "True"
 
if age < 18:
    print("Too young")
elif has_ticket:
    print("Enter")
else:
    print("Buy a ticket")

Type 25 and then False on the next line. The output is Buy a ticket. Try 15 and True. The output is Too young, because the first test is True and the program never uses the ticket answer for the decision.

The line has_ticket = input().strip() == "True" needs a word of explanation. input() gives back the text the user typed, so has_ticket cannot be a bool yet. The comparison with "True" turns the text into a bool. .strip() removes spaces around the text. Do not write has_ticket = bool(input()). The text "False" is not empty, so bool("False") gives True, and every guest would get in.

Indentation instead of braces

Many languages use curly braces to mark a block. Python uses indentation. The layout of the code is the structure of the program, so the compiler and the reader always agree.

This removes one famous trap. In languages with optional braces, an else can attach to the wrong if when the braces are missing. Python has no such problem, because the else lines up with exactly one if. Here is a nested test:

Python · editable
Pass

The else is indented to the same level as the inner if, so it belongs to the inner if. The score is 55. The outer test is True, the inner test is False, and the inner else prints Pass. If the score were 30, the outer test would be False, and the whole block would be skipped.

The indentation trap is different in Python. A line indented by mistake changes the meaning of the program, and a line that should be indented but is not changes it too. Compare these two programs. The second one has the print("done") line indented by mistake.

Python · editable
done
Python · editable

The second program prints nothing. Both print lines sit inside the if, and x > 5 is False. Nothing in the program says that you meant otherwise, so read the indentation carefully whenever a block seems to run too often or not at all.

Python gives clear messages when the indentation breaks the rules. Here is a block with no indented lines under the colon:

  File "main.py", line 3
    print("big")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

The message names the if line. Look at the line before the caret: the if needs an indented block under it.

Largest and smallest of three

A common exercise is finding the largest of three numbers. The method is to assume the first number is the largest, then compare each of the other numbers against the current winner. The program below does this for both the largest and the smallest value. Type 4, 9 and 6 on three lines.

a = int(input())
b = int(input())
c = int(input())
 
largest = a
if b > largest:
    largest = b
if c > largest:
    largest = c
 
smallest = a
if b < smallest:
    smallest = b
if c < smallest:
    smallest = c
 
print(f"largest {largest}, smallest {smallest}")

The output for 4, 9 and 6 is:

largest 9, smallest 4

Trace the largest first. largest starts as 4. b > largest is 9 > 4, which is True, so largest becomes 9. c > largest is 6 > 9, which is False, so nothing changes. The smallest follows the same steps with <.

These are two separate groups of if statements, not an elif chain. The two results do not compete with each other. Each if tests one new value against the running answer. Python also has the built-in functions max(a, b, c) and min(a, b, c), which give the same answers. Writing the comparisons yourself teaches the idea that the built-ins hide.

Try 7, 7 and 7 to check the equal case. Both answers are 7, which is correct. Also try -3, -10 and -1. The largest is -1 and the smallest is -10. Negative numbers follow the same comparisons as positive ones, so the code needs no special case.

Binary search is a chain of if decisions

Searching a sorted list is a good way to see how conditions drive a whole algorithm. Binary search checks the middle value. If the middle is the target, it stops. If the target is smaller, it keeps the left half. Otherwise, it keeps the right half. Each step makes one decision with an if, elif and else.

Python · editable
3
-1

The while loop repeats the decision until the answer is found. You will study loops in a later module, so for now read only the if part. The three outcomes of each step are equal, less and greater. Each step throws away half of the remaining values, which is why the search takes only a few steps even for a very long list.

Notice what happens when the target is not in the list. The search eventually runs out of values to keep, and the function reaches return -1. Writing that answer on purpose is what makes the function correct. The standard library also has bisect.bisect_left, which finds the position where a value would go in a sorted list. bisect.bisect_left([1, 3, 5, 7, 9, 11], 7) gives 3, the same index as the search above.

What happens inside

You do not need to understand the processor to use if, but one picture helps when a condition behaves in a way you do not expect.

Python does not run your text directly. It first turns the program into a list of smaller steps called bytecode. You can look at those steps with the dis module. On Python 3.14, each if becomes a compare step followed by a jump step. The jump says "skip this block" when the comparison is False. Other Python versions use other step names, but the idea is the same.

A chain of elif is a chain of compare-and-jump steps in order. This explains why the order matters. Python really does check the first comparison, then the next one, until one of them says to run its block. The rest are never checked.

For and and or, Python places a jump after the first test. If the first test already gives the answer, the jump skips the second test. That is the mechanism behind short-circuit evaluation. Nothing magic happens, only a jump that the translated program contains.

A condition often reads variables, and reading a variable has no side effect. Keep your conditions simple, and they will be easy to reason about. A condition that calls a function which prints or changes data is harder to follow.

Turning a rule into a condition

Programs begin with rules written in plain language, and your job is to turn each rule into a test the computer can run. Four steps make the translation reliable.

  1. Name the values involved and give each one a variable.
  2. Rewrite the rule as a yes-or-no question about those variables.
  3. Check the boundary words. "At least" means >=, "more than" means >, "at most" means <=, and "fewer than" means <.
  4. Decide what happens when the question is True, and what happens when it is False. Make sure both answers are covered.

Here is a worked example. A library rule says: a book returned after its due date costs 25 pence for each late day, with a maximum fee of 500 pence. A book returned on or before its due date costs nothing. Print the fee for a book that is 12 days late.

Python · editable
Fee: 300 pence

Trace it. Step 1: days_late is 12. Step 2: the question "is the book late?" becomes days_late > 0. The word "after" means strictly later, so > is correct, and a book returned on the due date has days_late of 0. Step 3: the fee is 12 * 25, which is 300. Step 4: the inner test asks whether 300 is more than the cap of 500. It is not, so the fee stays 300.

Now change the value to 30 late days. The fee is 30 * 25, which is 750. The inner test is 750 > 500, which is True, so fee becomes 500. Change it to 0 and the outer test is False, so fee keeps its starting value of 0. Three inputs, three branches, and each boundary is covered: the on-time case, the normal case and the capped case.

The boundary words are where most translations go wrong. The rule says "on or before the due date", so the on-time case must include 0. If you wrote days_late >= 0 as the late test, every book would be treated as late, including the ones returned on time. Reading the rule word by word, and matching each boundary word to an operator, prevents this mistake before you run the code.

Variations you will see

Real Python code uses a few variations of the basic if. Each one is correct, but each reads differently, so learn to recognise them.

A negation with not reads as "if not". if not is_open: runs its block when is_open is False. Using not on a name that is already a question, such as is_open, reads more naturally than comparing with False.

A test for membership uses in. if c in ("a", "e", "i", "o", "u"): is True when c is one of the five letters. It is shorter than five or tests, and it reads as the rule does.

Comparing with None uses is, as in if value is None:. The is operator asks whether two names refer to the same object, and None is a single object, so is is the right check. value == None also runs, but the style guide for Python asks for is.

Python accepts a number where a bool is expected. if 1: runs its block, because any non-zero number counts as True. The statement is valid, but it hides intent. Write a real comparison whenever you can.

Python also has a one-line form of if. It is called a conditional expression, and it reads value_if_true if condition else value_if_false:

Python · editable
Take a coat

Use it for a short choice between two values. Use the full if block when either branch does more than one thing.

The single & and | operators look like and and or to a beginner. Do not use them for conditions. Python's & and | work on numbers as bit patterns, and they do not short-circuit. Use and and or for every condition in this lesson.

Check your conditions with a table of cases

Before you trust a condition, write a table. Each row is one input, the output you expect, and the trace that gets there. The table turns a vague feeling that the code is right into a list you can check line by line. It also catches the boundary mistakes that a single test misses, because it forces you to choose the values on the edges.

Here is a table for the grade ladder from earlier. The bands are 90 and above for A, 75 to 89 for B, 60 to 74 for C, and 59 and below for Fail.

mark   expected    trace
100    Grade A     100 >= 90 is True
90     Grade A     90 >= 90 is True
89     Grade B     89 >= 90 is False, 89 >= 75 is True
75     Grade B     75 >= 90 is False, 75 >= 75 is True
74     Grade C     74 >= 75 is False, 74 >= 60 is True
60     Grade C     60 >= 90 and 60 >= 75 are False, 60 >= 60 is True
59     Grade Fail  every test is False

Read the table in pairs. Each cut-off has a value that just reaches it and a value just below it, such as 90 and 89, or 75 and 74. A wrong > in place of >= shows up at once. If the test at 90 used >, the row for 90 would print Grade B, which does not match the expected column, so the table exposes the bug before the program runs.

Write the table before you write the code. It takes a couple of minutes. Then run the program with each input in the first column and compare the output with the middle column. A mismatch points you at one row, and the trace column shows which test went wrong.

Good tables include three kinds of row: a typical value, a value on each boundary, and an invalid value when the program should reject one. A table with only typical values is the most common reason a program passes a quick check and then fails in real use.

Common mistakes and the messages Python gives you

Each of these mistakes has a recognisable message or behaviour. Learn to read them, because they point straight at the problem. The message shows the line number, and the caret (^) points at the place where Python got confused.

Mistake 1: = instead of ==. You write if x = 5: and expect a comparison. Python reports:

  File "main.py", line 2
    if x = 5:
       ^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

The = stores a value and cannot appear where a condition is expected. Change = to ==.

Mistake 2: comparing text with a number. You write if s == 5: when s holds the text "a". Python does not stop. The comparison gives False, and the block is skipped. This is different from some other languages, which refuse to compile the same line. Python's silence is the danger here, because the program runs and quietly takes the wrong branch. Remember that input() returns text, and convert it with int(...) before a number comparison.

Mistake 3: a missing colon. You write if x > 2 and leave out the colon. Python reports:

  File "main.py", line 2
    if x > 2
            ^
SyntaxError: expected ':'

Every if, elif, else, for and while line ends with a colon.

Mistake 4: no indented block. You write the colon and forget to indent the next line. The message is the IndentationError shown in the earlier section, and it names the if line.

Mistake 5: a line indented too far. A line in the middle of a block is indented more than the lines around it. Python reports IndentationError: unexpected indent. The line above the caret is usually the one with the wrong indentation.

Mistake 6: else after an if that was closed too early. You put a line between an if block and its else, at the if level. Python reports SyntaxError: invalid syntax at the else, because the else no longer has an if to attach to.

Mistake 7: elif after else. Once a chain reaches else, it is finished. Python reports:

SyntaxError: 'elif' block follows an 'else' block

Move the elif above the else.

Mistake 8: a broad test hides a narrow one. Your program prints the wrong answer, and no error appears. This is the ordering bug. The fix is to move the narrow test above the broad one. Test your program with the boundary values, not just a typical one. For the grade ladder, check 59, 60, 74, 75, 89, 90 and 100.

Mistake 9: two separate if statements where you meant one answer. Two if statements each test the original data, so both can be True. If you want one answer, use elif.

Mistake 10: text that is not a number. You type abc when the program expects a whole number. Python reports:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    n = int(input())
ValueError: invalid literal for int() with base 10: 'abc'

The message names the text that could not be converted. Real programs check the input before converting it. Typing 2.5 gives the same error, because int accepts only whole numbers.

Debugging walkthrough: a grade that is always wrong

Suppose a student wrote the grade program below and reports that a mark of 90 prints B. The student expects A. Here is how to find the bug.

if marks > 90:    -> A
elif marks >= 75: -> B

Step 1: write down the input. It is 90.

Step 2: evaluate the first test. 90 > 90 is False, because > means strictly greater than.

Step 3: evaluate the second test. 90 >= 75 is True, so B prints.

The bug is the operator. The requirement says "90 to 100 is A", which includes 90. The test should be marks >= 90. This is the kind of bug that tests at the boundary find, which is why you should always test the exact cut-offs. Change the operator, then rerun with 90, 89 and 75. The results should be A, B and B.

A second technique is to add a temporary print at each branch, such as print("in A branch"). The printed text shows you which branch ran. Remove the prints when you are done. For a problem this small, reasoning by hand is faster, but the prints help when the chain is long.

Interview questions about conditionals

Interviewers ask conditional questions because they test whether you can turn words into correct tests and whether you test the edges. Three patterns come up over and over.

The first is the range check. For a value that must lie between low and high, write low <= value <= high. Remember that the boundaries are included, and say so in your answer. If the question says "strictly between", use < on both sides.

The second is the guard clause. A guard checks for invalid input at the very start and returns or prints an error before any other test. Guards keep the main logic flat and easy to read. You will use them in the later lessons of this module and in every module after it.

The third is the sign test. Compare a number with 0 to find whether it is positive, negative or zero. Most interviewers expect you to list all three cases, including zero, and to say which one is the easy one to forget. Zero is the case people forget when they write only if n > 0: and an else.

Each of these checks is a fixed number of comparisons, no matter how big the input is. Time complexity is O(1) for a single if, meaning the work does not grow with the input. A chain with ten elif tests does ten comparisons in the worst case, which is still a constant. Conditionals do not make a program slow by themselves. Loops over large inputs are what matter, and you will meet those in the next modules.

Real-world uses

Every app uses these patterns constantly. A login check tests whether the password matches and whether the account is locked. A shopping cart applies a discount only when the total is above a threshold and the coupon has not expired. A thermostat switches heating on below one temperature and off above another, using two tests that must not overlap. A game decides whether a player touched a wall. Each of these is a condition combined with and or or, followed by a branch.

When you read real code, look for three things: the order of the tests, the boundaries (is it > or >=?), and any guard that protects a risky operation such as a division or a None lookup. Those three checks find most bugs in conditional code.

Practice

Each exercise has an answer below it. Try it on your own first, then read the answer to compare. Type the sample inputs when your program asks for them.

  1. Read one integer and print even if it is even, or odd if it is odd. Hint: the remainder of a division by 2 is 0 for even numbers.

Show the answer

n = int(input())
if n % 2 == 0:
    print("even")
else:
    print("odd")

Test -3. In Python, -3 % 2 is 1, so the program prints odd. The remainder never comes out negative when the divisor is positive, so no special case is needed.

  1. Read an age and print child for ages under 13, teen for ages from 13 to 19, and adult for 20 and above. Test the boundaries 12, 13, 19 and 20.

Show the answer

Use an elif ladder. Test age < 13 first, then age < 20, then the else for everything else. Because the second test is only reached when age is at least 13, you do not need to write age >= 13 again.

age = int(input())
if age < 13:
    print("child")
elif age < 20:
    print("teen")
else:
    print("adult")
  1. Read a temperature in whole degrees and print freezing at 0 or below, cold below 15, warm below 25, and hot otherwise. Choose the order of the tests so each one is short.

Show the answer

Test the lowest band first: temp <= 0, then temp < 15, then temp < 25, then else. Each later test only has to handle the values that the earlier tests rejected.

temp = int(input())
if temp <= 0:
    print("freezing")
elif temp < 15:
    print("cold")
elif temp < 25:
    print("warm")
else:
    print("hot")
  1. Read one integer and print in range if it is from 10 to 20 inclusive, and out of range otherwise. Use one if with and, then rewrite the condition as a chained comparison.

Show the answer

n = int(input())
if n >= 10 and n <= 20:
    print("in range")
else:
    print("out of range")

The chained form is if 10 <= n <= 20:. Both boundaries are included, because the operators are >= and <=.

  1. Read two integers and print equal, first is larger or second is larger. Hint: the first test is equality.

Show the answer

a = int(input())
b = int(input())
if a == b:
    print("equal")
elif a > b:
    print("first is larger")
else:
    print("second is larger")

Test a == b first. Then test a > b. Otherwise the second number must be larger, so the else covers it. Remember that == is the comparison, and = would be a syntax error here.

  1. Read one character. Print yes if it is y or Y, and no otherwise. Hint: input() returns text, so compare it with a string in quotes.

Show the answer

c = input().strip()
if c == "y" or c == "Y":
    print("yes")
else:
    print("no")

The strip() call removes spaces around the typed letter. The membership form if c in ("y", "Y"): also works.

  1. Read three integers and print the middle one. Hint: a value is in the middle when it lies between the other two, in either order. Try the rule on the numbers 4, 9, 6 and on 5, 5, 1.

Show the answer

Test b first. It is the middle when it lies between the other two, in either order. Then test a the same way. If neither passes, c must be the middle.

a = int(input())
b = int(input())
c = int(input())
if a <= b <= c or c <= b <= a:
    mid = b
elif b <= a <= c or c <= a <= b:
    mid = a
else:
    mid = c
print(mid)

For 4, 9, 6, the first test fails, the second test fails, and the answer is c, which is 6. For 5, 5, 1, the first test passes (1 <= 5 <= 5), so the answer is 5. The <= operators count equal values, which is why duplicates work.

  1. Predict the output of this program, then run it to check.
x = 3
if x > 5:
    print("big")
    print("done")
print("end")

Show the answer

The output is end. Both print lines are indented under the if, so they are skipped when x > 5 is False. The last line is not indented, so it always runs. Indent only the lines that belong to the test.

  1. Fix this grade function so that every score gets the correct letter. It should return A for 90 and above, B for 75 to 89, C for 60 to 74, and F otherwise.
def grade(marks):
    if marks >= 60:
        return "C"
    elif marks >= 75:
        return "B"
    elif marks >= 90:
        return "A"
    return "F"

Show the answer

The order is wrong. The first test catches every mark from 60 up, so the B and A tests are never reached. Put the highest cut-off first:

def grade(marks):
    if marks >= 90:
        return "A"
    elif marks >= 75:
        return "B"
    elif marks >= 60:
        return "C"
    return "F"

Scores of 95, 80, 65 and 40 now give A, B, C and F.

  1. Write a condition that tests whether a number n is a valid index into a list of length 10, which means 0 to 9 inclusive. Explain why Python accepts 0 <= n < 10 as one expression.

Show the answer

n = int(input())
if 0 <= n < 10:
    print("valid index")

Python reads a chained comparison as two tests joined by and. The first test is 0 <= n, and the second is n < 10. In languages without chains, 0 <= n < 10 is read as (0 <= n) < 10, which compares a bool with a number, so they need 0 <= n && n < 10.

  1. A shop gives 10 percent off when a bill is at least 100 units, and 5 percent off when a bill is at least 50 units. Read the bill as an integer and print the amount to pay as an integer, rounded down. Hint: use //, which is integer division.

Show the answer

bill = int(input())
if bill >= 100:
    print(bill * 90 // 100)
elif bill >= 50:
    print(bill * 95 // 100)
else:
    print(bill)

Test 120 (the output is 108) and 60 (the output is 57). The 100 test comes first, so a bill of 120 never gets the 5 percent rule. The // operator drops the fraction, which matches the rule.

  1. Write a guard that protects a division. Read two integers and print a // b when b is not zero, and no division otherwise. Put the guard first so the division never runs when b is zero.

Show the answer

a = int(input())
b = int(input())
if b != 0:
    print(a // b)
else:
    print("no division")

This is the same guard idea as the d != 0 and 100 / d > 10 example, written as nested branches. The / operator would print 3.5 for 7 divided by 2, because it always gives a float. The // operator gives the whole-number answer, 3.

What you now know

  • A condition is a question with a True or False answer, built with comparison operators.
  • if runs a block only when its condition is True. else runs when it is False. elif tests the next condition in a chain.
  • An elif chain runs the first True block and skips the rest, so the order of the tests matters.
  • and, or and not combine conditions, and and and or skip the right side when the answer is already known.
  • Python uses indentation for blocks, and every if line ends with a colon.
  • Values such as 0, "", [] and None count as False in a condition. Check for None with is None when 0 is a valid value.
  • Watch for the = and == mix-up, a missing colon, and boundary operators that should be >= but are written >.
Practice this topic: coding problems for Conditionals →

Stuck? Ask the tutor

Ask about anything in this lesson. Answers are short and use simple words.

Sign in to ask the tutor.