Skip to content
Study Hall
Lesson 3 of 3Coding with Python
Unit 4 · Lesson 3 of 3

Conditionals, Inequalities and Altering Code

Use comparison operators as inequalities, make decisions with if, elif and else, test which values satisfy an inequality, and read and alter a program that compares two phone plans.

8 min read8 quick checks12 practice questionsInteractiveAsk AI about this →

Key things to remember

  1. 1Comparison operators: <, >, <= (), >= (), == (), != (). Each gives True or False.
  2. 2In an if, elif, else chain Python runs the block under the first True condition, or the else block if none is True, so exactly one block runs.
  3. 3A loop with an if inside tests an inequality for every value in the range; the printed values are the solutions among the values tested, not all solutions.
  4. 4> and < leave out the boundary value; >= and <= include it. "At least 50" is >= 50.
  5. 5To alter a program for a new situation, change its parameters (fees, rates), its range, or its conditions, then predict and check the new output.

Plan A for a phone costs 20 dollars a month plus 5 dollars per gigabyte (GB) of data. Plan B costs 40 dollars a month plus 1 dollar per GB. Which is cheaper? It depends: for a light user Plan A wins, for a heavy user Plan B wins. The question "is Plan A cheaper?" is an inequality, , and its answer is true for some values of and false for others. Programs make decisions the same way. A condition is a comparison that is either True or False, and a conditional (an if statement) runs some lines only when its condition is True. Put a conditional inside a loop and the program can test an inequality for many values at once.

Comparisons are inequalities

MathPythonExample with x = 7Result
(less than)<x < 10True
(greater than)>x > 10False
(less than or equal to)<=x <= 7True
(greater than or equal to)>=x >= 8False
(equal to)==x == 7True
(not equal to)!=x != 7False
Python's six comparison operators. Each one gives True or False.
x = 7
print(x > 5)
print(x <= 7)
print(2 * x == 14)
print(x != 7)
Output, one per line: True, True, True, False.
Quick checkTry it before you read on
1
The variable x holds 6. Which line prints False?
Quick checkTry it before you read on
2
What does print(5 < 5) print?

Making decisions with if, elif and else

n = -4
if n > 0:
    print("positive")
elif n < 0:
    print("negative")
else:
    print("zero")
Output: negative. With n = 0, the output would be zero.

Like a loop, each if, elif and else line ends with a colon, and the indented lines under it belong to it. Python checks the conditions from the top down. It runs the block under the first condition that is True and skips everything else in the chain. elif (short for "else if") is checked only when every condition above it was False, and else has no condition: it runs when none of the conditions above it were True. So in an if, elif, else chain exactly one block runs. Both elif and else are optional; an if on its own simply runs its block or skips it. For , the test is False, the test is True, so the program prints negative and never reaches else.

Trace for n = −4n = -4n holds −4if n > 0:−4 > 0 is False print("positive")skippedelif n < 0:−4 < 0 is True print("negative")runs: prints negativeelse:not checked print("zero")skippeddone: the rest of the chain is skippedThree runs of the chainnn > 0?n < 0?prints5True—positive0FalseFalsezero−4FalseTruenegative— means not checked: an earliertest was already True.Python tests from the top and runsonly the first True block, so exactlyone block runs each time.
Fig 1The if, elif, else chain traced for n = -4. The test n > 0 is False, so Python moves down; the test n < 0 is True, so it prints negative and skips the else block. A table shows the path for n = 5, n = 0 and n = -4: exactly one block runs each time.
Quick checkTry it before you read on
1
What does this program print?temp = 12 if temp > 25: print("hot") elif temp > 10: print("mild") else: print("cold")
Quick checkTry it before you read on
2
What does this program print?n = 0 if n >= 0: print("A") elif n == 0: print("B") else: print("C")
VideoKhan Academy traces a chain of if, elif and else branches to show that Python checks the conditions in order and runs only the first branch whose condition is True.Watch on YouTube

Testing an inequality with a loop

for x in range(0, 11):
    if 3 * x + 2 > 14:
        print(x)
Output: 5, 6, 7, 8, 9 and 10, each on its own line.

The loop substitutes into and prints only the values that make true. At the left side is exactly 14, and is False, so 4 is not printed; changing > to >= would add it. Algebra gives the complete answer: subtract 2 from both sides to get , then divide by 3 to get . The two agree, but they are not the same thing. The loop tests only the whole numbers in its range, so it says nothing about 4.5 or 50, both of which also satisfy . Testing with code is a quick way to check a solution or spot a pattern; algebra describes every solution. To test a value between two bounds, such as , Python lets you write 2 <= x <= 6, or join two conditions with and: x >= 2 and x <= 6.

The loop tests each whole number in range(0, 11)3x + 2> 14?printed2no5no8no11no14no17yes20yes23yes26yes29yes32yes0123456789101112not testedx > 401234567891011124.511Algebra: 3x + 2 > 14, so 3x > 12, so x > 4. Every value right of the open circleworks, including 4.5 and 11, which the loop never tests.
Fig 2Each whole number from 0 to 10 tested in 3x + 2 > 14. The dots for 5 to 10 are filled because the loop prints them; 0 to 4 are not, and at x = 4 the left side is exactly 14. Below, the algebra solution x > 4 is a ray with an open circle at 4, which also covers values the loop never tests, such as 4.5 and 11.
Quick checkTry it before you read on
1
The lesson's loop over range(0, 11) tests and prints 5, 6, 7, 8, 9 and 10. Which of these values also makes true, but is never printed?
Quick checkTry it before you read on
2
What is the first number this program prints?for x in range(0, 11): if x + 5 >= 9: print(x)

Reading and altering code: two phone plans

fee_a = 20
rate_a = 5
fee_b = 40
rate_b = 1

for gb in range(0, 9):
    cost_a = fee_a + rate_a * gb
    cost_b = fee_b + rate_b * gb
    if cost_a < cost_b:
        print(gb, cost_a, cost_b, "Plan A")
    elif cost_a > cost_b:
        print(gb, cost_a, cost_b, "Plan B")
    else:
        print(gb, cost_a, cost_b, "same")
Output: 0 20 40 Plan A up to 4 40 44 Plan A, then 5 45 45 same, then 6 50 46 Plan B up to 8 60 48 Plan B.
cost_a = 20 + 5 * gbcost_b = 40 + gbcost_a < cost_b?ifyesprint: Plan Anocost_a > cost_b?elifyesprint: Plan Bnoelseprint: sameExactly one branch runs for each value of gb.Branch that runs for each gb012345678gigabytes (gb)Plan A: 0 to 4 GBsame: 5 GB (both cost 45)Plan B: 6 to 8 GBPlan A is cheaper when20 + 5g < 40 + g4g < 20g < 5
Fig 3Flowchart of the if, elif, else chain: if cost_a is less than cost_b, print Plan A; otherwise, if cost_a is greater, print Plan B; otherwise print same. A number line shows Plan A for 0 to 4 GB, same at 5 GB and Plan B for 6 to 8 GB, matching the algebra 4g < 20, so g < 5.

Reading code means predicting what it does before you run it. For 3 GB, and ; the first condition is True, so that line is 3 35 43 Plan A. Altering code means changing it to model a new situation, and the parameters at the top make that easy. If Plan B's monthly fee rises to 45 dollars, change one line to fee_b = 45. Now Plan A is cheaper while , that is , or : the lines for 0 to 6 GB say Plan A, 7 and 8 GB say Plan B, and no line says same, because 6.25 is not a whole number. To compare up to 20 GB, change the range to range(0, 21). Each change is a small edit to one line, and the loop and conditions do the rest.

Loading interactive…
Choose the if-elif-else, inequality or phone-plan program and step through it to see which condition is True and which line runs.
Quick checkTry it before you read on
1
In the phone-plan program (Plan A: fee_a = 20, rate_a = 5; Plan B: fee_b = 40, rate_b = 1), what line is printed when gb is 2?
Quick checkTry it before you read on
2
In the phone-plan program, the line rate_b = 1 is changed to rate_b = 3. At how many GB do the two plans now cost the same?
GB

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
This program decides where the point (4, 15) is compared with the line . Predict its output.x = 4 y = 15 if y == 2 * x + 5: print("on the line") elif y > 2 * x + 5: print("above the line") else: print("below the line")
Example 2
How many integers from to satisfy ? Write a program to count them, then check with algebra.
Example 3
In the phone-plan program from the lesson, predict the lines printed for 5 GB and for 7 GB.
Example 4
Plan A raises its rate to 6 dollars per GB (the fee stays 20 dollars). Which line of the phone-plan program do you change, and at how many GB do the plans now cost the same?

Where marks get lost

  • Typing => or =<. Python's operators are >= and <=, with the equals sign second; the other order is a SyntaxError.
  • Using one equals sign in a condition, as in if x = 5:. That is a SyntaxError; comparing uses ==.
  • Using > when the boundary should count. "At least 50" includes 50, so it is >= 50; > 50 leaves 50 out.
  • Ordering an elif chain badly. In if x > 0: followed by elif x > 10:, the second block can never run, because every x greater than 10 is already caught by the first test. Put the narrower test first.
  • Treating a loop's output as every solution. A loop over range(0, 11) tests only the whole numbers 0 to 10; the inequality is also true for 4.5, 11 and 1000.

Flashcards 7

Condition
!=
<= and >=
if / elif / else
+ 3 more

Practice

1
Which Python condition means ?
2
What does this program print?t = 0 if t > 0: print("positive") elif t < 0: print("negative") else: print("zero")
3
How many numbers does this program print?for x in range(1, 21): if 4 * x - 3 > 50: print(x)
numbers
4
Match each Python operator to its math symbol.
  1. A.
  2. B.
  3. C.
  4. D.
  5. E.
<=
>=
!=
==
<
5
In the lesson's phone-plan program (Plan A: 20 dollars plus 5 dollars per GB; Plan B: 40 dollars plus 1 dollar per GB), what line is printed when gb is 5?
6
The lesson's phone-plan program compares Plan A (fee_a = 20, rate_a = 5) with Plan B (fee_b = 40, rate_b = 1). The line fee_b = 40 is changed to fee_b = 45 and the loop still runs over range(0, 9). How many of the 9 printed lines say Plan A?
lines
7
What does print(3 * 4 > 10) print?
8
A program should print "pass" when score is 50 or more. It uses if score > 50:. What is wrong, and what is the fix?
9
Put these lines in order to count the whole numbers from 1 to 20 that satisfy and print the count once.
  1. 1print(count) (not indented)
  2. 2 count = count + 1 (indented twice)
  3. 3 if 5 * x + 1 >= 30: (indented once)
  4. 4count = 0
  5. 5for x in range(1, 21):
10
Where is the point (2, 9) compared with the line ? This program decides.x = 2 y = 9 if y == 3 * x + 2: print("on the line") elif y > 3 * x + 2: print("above the line") else: print("below the line")
11
How many numbers does this program print?for x in range(-3, 10): if -1 < x <= 4: print(x)
numbers
12
The lesson's phone-plan program starts with the parameters fee_a = 20, rate_a = 5, fee_b = 40 and rate_b = 1. To model Plan A raising its rate to 6 dollars per GB, which single line should you change?

Spot a mistake on this page? Let us know