Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 11

Decisions: if, elif, else

This lesson goes with Episode 11 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

11.1 The if statement

Here is a decision in Python:

temperature = 34
if temperature > 30:
    print("It is hot today.")
    print("Drink plenty of water.")
print("Have a nice day.")

Output

It is hot today.
Drink plenty of water.
Have a nice day.

Change the temperature to 22 and run it again:

temperature = 22
if temperature > 30:
    print("It is hot today.")
    print("Drink plenty of water.")
print("Have a nice day.")

Output

Have a nice day.

The two indented lines ran the first time and were skipped the second time. The last line ran both times.

The parts of an if

    keyword    condition     colon
       │           │           │
       if  temperature > 30    :
           print("It is hot today.")          ┐  the block (or body):
           print("Drink plenty of water.")    ┘  runs only if True
       print("Have a nice day.")                 not indented: always runs
       └──┘
     4 spaces
  • if is a keyword.
  • The condition is any expression. Python works it out and looks at whether the result is truthy or falsy (Chapter 5).
  • The colon : ends the first line. It announces "a block follows".
  • The block (also called the body) is the group of indented lines underneath. If the condition is true, the whole block runs. If it is false, the whole block is skipped.
  • The first line that is not indented is outside the if. The program always continues there.

Here is the same thing as a picture of the path the program takes:

              │
              ▼
      ┌────────────────┐   False
      │ temperature>30 ├───────────┐
      └───────┬────────┘           │
         True │                    │
              ▼                    │
     ┌─────────────────┐           │
     │   the block     │           │
     └────────┬────────┘           │
              ├◄───────────────────┘
              ▼
       "Have a nice day."

The condition is checked once, at the moment the program reaches that line. If temperature changes later, the if does not go back and run again.

Quick check

What does this print when stock is 0? And when it is 5?

if stock == 0: ⏎ (indented) print("Sold out") ⏎ (not indented) print("Thank you")

Show the answer

Answer: with 0 it prints Sold out and then Thank you. With 5 it prints only Thank you.

Practice 11.1

Predict the output

What does it print?

speed = 45
if speed > 50:
    print("Slow down.")
    print("The limit is 50.")
print("Drive safely.")
if speed > 40:
    print("Nearly at the limit.")

Put the lines in order

Put the lines in order. The message about the stock must come before the thanks, and the thanks must be shown for every value of stock.

The program in the right order prints:

Target

Sold out
Thank you
  1. print("Thank you")
  2. stock = 0
  3. if stock == 0:
  4. print("Sold out")

11.2 Indentation is the grammar

In many programming languages, blocks are wrapped in curly brackets, and indentation is only decoration. In Python, the indentation is the structure. Python decides which lines belong to an if purely by how far they are indented. There is nothing else.

That has one big advantage: the code looks like what it does. A reader can see the structure at a glance. It also means you must be exact.

The rules

  1. The line that opens a block ends with a colon.
  2. Every line of the block is indented by the same amount. The universal convention, from the style guide PEP 8, is four spaces.
  3. The block ends at the first line that goes back to the earlier indentation level. Going back is called dedenting.

In VS Code you do not count spaces. Press Tab once and the editor inserts four spaces. After a line ending in a colon, pressing Enter indents the next line for you. Shift+Tab removes one level.

Indentation changes the meaning

These two programs differ by four spaces, and they do different things:

balance = 50
price = 80
if balance >= price:
    print("Payment accepted.")
    print("Enjoy your purchase!")

This first program prints nothing at all.

balance = 50
price = 80
if balance >= price:
    print("Payment accepted.")
print("Enjoy your purchase!")

Output

Enjoy your purchase!

In the first program both lines are inside the if, and since 50 is less than 80, the whole block is skipped. In the second, the last line has been dedented, so it is outside the if and always runs. A customer with too little money is told to enjoy the purchase. No error message will ever point this out. It is a logic error, and the only way to see it is to look at the indentation.

The three indentation errors

No block at all. An if must have at least one indented line under it:

age = 20
if age >= 18:
print("Welcome")

Output

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

Indentation with no reason. You cannot indent a line unless a line with a colon opened a block:

age = 20
    print("Welcome")

Output

  File "door.py", line 2
    print("Welcome")
IndentationError: unexpected indent

Dedenting to a level that does not exist. A line must go back to a level that an earlier line used:

age = 20
if age >= 18:
    print("Welcome")
  print("Come in")

Output

  File "door.py", line 4
    print("Come in")
                    ^
IndentationError: unindent does not match any outer indentation level

The last line has two spaces. That matches neither the if (zero spaces) nor its block (four).

Forgetting the colon

age = 20
if age >= 18
    print("Welcome")

Output

  File "door.py", line 2
    if age >= 18
                ^
SyntaxError: expected ':'

Everyone forgets the colon. Python tells you exactly what is missing.

Practice 11.2

Multiple choice

What happens when this program is run?

years = 20
if years >= 18:
print("Welcome")
Choose one answer

Fix the bug

The price is 80 dollars. A customer with a balance of 50 is still told to enjoy the purchase. Fix the program so that this message is shown only when the payment is accepted. The goodbye line must always be shown.

With the reply 50, the program prints the lines below. Your program must print exactly these lines.

Example run

Goodbye.

11.3 Two paths: else

Often you want to do one thing when the condition is true and a different thing when it is false. Add an else block:

age = int(input("Your age: "))
if age >= 18:
    print("You can vote.")
else:
    print("You cannot vote yet.")
    print("Years to wait:", 18 - age)
print("Thank you.")

Output

Your age: 15
You cannot vote yet.
Years to wait: 3
Thank you.
                 │
                 ▼
         ┌───────────────┐
   True  │   age >= 18   │  False
  ┌──────┤               ├──────┐
  │      └───────────────┘      │
  ▼                             ▼
┌──────────────┐      ┌──────────────────┐
│  if block    │      │   else block     │
└──────┬───────┘      └────────┬─────────┘
       └──────────┬────────────┘
                  ▼
             "Thank you."

Three facts about else:

  • It has no condition. It means "in every other case".
  • It lines up with its if (same indentation), and it also ends with a colon.
  • Exactly one of the two blocks runs. Never both, never neither.

An else cannot exist on its own. It always belongs to the if directly above it at the same level.

A classic: even or odd

number = 7
if number % 2 == 0:
    print(number, "is even")
else:
    print(number, "is odd")

Output

7 is odd

A number is even when dividing by 2 leaves no remainder (Chapter 4). There are only two possibilities, so if/else fits perfectly.

Practice 11.3

Fill in the blank

Fill in the keyword that starts the second path.

number = int(input("Number: "))
if number % 2 == 0:
    print(number, "is even")
:
    print(number, "is odd")

With the reply 7, the finished program prints:

Target

7 is odd

Write code

Free delivery. Ask for the total of an order in dollars (it can be a decimal number). If the total is 40 or more, print Free delivery. Otherwise print Delivery costs 5 dollars.

With the reply 40, the program prints the lines below. Your program must print exactly these lines.

Example run

Free delivery

11.4 Many paths: elif

For more than two possibilities, add elif blocks between the if and the else. elif is short for "else if":

marks = int(input("Marks out of 100: "))
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
elif marks >= 40:
    grade = "D"
else:
    grade = "F"
print("Grade:", grade)

Output

Marks out of 100: 73
Grade: C

How a chain is worked out

Python tests the conditions from the top, one at a time. The moment one is true, it runs that block and then jumps past the entire rest of the chain. If none is true, the else block runs.

For marks = 73:

Step Condition Result What happens
1 73 >= 90 False move on
2 73 >= 75 False move on
3 73 >= 60 True run grade = "C", then leave the chain
4 73 >= 40 never checked
5 else never reached

Notice step 4. 73 >= 40 would be true, but it is never even looked at. In a chain, at most one block runs: the first one whose condition is true.

This is what lets each condition be so short. To reach elif marks >= 60, the program must already have failed marks >= 90 and marks >= 75, so at that point we know the marks are below 75. There is no need to write 60 <= marks < 75. Each elif silently includes "...and none of the earlier ones were true".

The rules for a chain

Part How many Position
if exactly one first
elif zero or more in the middle
else zero or one last

The else is optional. Without it, if no condition is true, nothing in the chain runs.

Order matters

Because the first true condition wins, a chain can be completely broken by putting the conditions in the wrong order:

marks = 95
if marks >= 40:
    grade = "D"
elif marks >= 60:
    grade = "C"
elif marks >= 75:
    grade = "B"
elif marks >= 90:
    grade = "A"
else:
    grade = "F"
print("Grade:", grade)

Output

Grade: D

A student with 95 gets a D. 95 >= 40 is true, so the first block wins and the rest is never checked. No error, of course.

Quick check

With the correct grade chain above, what grade do marks of 90, 75, 74 and 39 get?

Show the answer

Answer: A (90 is >= 90), B (75 is >= 75), C and F. The boundary values are the ones worth testing by hand.

Practice 11.4

Predict the output

What does it print?

hour = 15
if hour < 12:
    print("morning")
elif hour < 18:
    print("daytime")
elif hour < 22:
    print("evening")
else:
    print("night")
print("done")

Multiple choice

In one if/elif/else chain, the second and the third condition are both true for some value. Which blocks run?

Choose one answer

Fix the bug

The program should print steam from 100 degrees up, water for temperatures above 0 and below 100, and ice for 0 or less. For 120 it prints water. Fix it.

With the reply 120, the program prints the lines below. Your program must print exactly these lines.

Example run

steam

11.5 A chain or separate ifs?

These two programs look similar and behave very differently.

One chain: the blocks are alternatives. At most one runs.

number = 12
if number % 2 == 0:
    print("divisible by 2")
elif number % 3 == 0:
    print("divisible by 3")
elif number % 4 == 0:
    print("divisible by 4")

Output

divisible by 2

Separate ifs: each one is an independent question. Any number of them can run.

number = 12
if number % 2 == 0:
    print("divisible by 2")
if number % 3 == 0:
    print("divisible by 3")
if number % 4 == 0:
    print("divisible by 4")

Output

divisible by 2
divisible by 3
divisible by 4
Use When the cases are... Example
if / elif / else alternatives: only one can apply a grade, a ticket price band, a menu choice
separate if statements independent: several can apply at once toppings on a pizza, a list of warnings

Choosing the wrong one is a common logic error. If you want exactly one outcome, use a chain. A chain is also slightly faster, because Python stops checking at the first match.

Practice 11.5

Predict the output

What does it print?

number = 30
if number % 2 == 0:
    print("two")
if number % 3 == 0:
    print("three")
elif number % 5 == 0:
    print("five")
if number % 10 == 0:
    print("ten")

Fix the bug

A ticket is free for children under 5, half price for children under 13 and full price for everybody else. Exactly one line should be printed, but for 3 this program prints two lines. Fix it.

With the reply 3, the program prints the lines below. Your program must print exactly these lines.

Example run

free

11.6 Decisions inside decisions: nesting

A block can contain any statements, including another if. This is called nesting. The inner if is indented one more level, eight spaces in total:

age = 25
has_ticket = True

if age >= 18:
    if has_ticket:
        print("Welcome to the concert.")
    else:
        print("You need a ticket.")
else:
    print("Sorry, adults only.")

Output

Welcome to the concert.

The inner if/else is only reached when age >= 18 is true. Each else belongs to the if it lines up with: the first else (eight spaces) pairs with if has_ticket, and the second (zero spaces) with if age >= 18.

Do not nest more than you need

Nesting is sometimes necessary, but every level makes code harder to follow. Two techniques flatten it.

Combine conditions with and. Two nested ifs with nothing in between are the same as one if with and:

age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("Welcome to the concert.")

Output

Welcome to the concert.

Deal with the problem cases first. Turn a deep pyramid into a flat chain by checking what is wrong at the top:

age = 25
has_ticket = False

if age < 18:
    print("Sorry, adults only.")
elif not has_ticket:
    print("You need a ticket.")
else:
    print("Welcome to the concert.")

Output

You need a ticket.

This flat version gives the same three outcomes as the nested one, and reads from top to bottom like a checklist. As a rule of thumb, if you are indenting a third level, look for a way to flatten.

Practice 11.6

Put the lines in order

Put the lines in order. For a number above zero, the program says whether it is even or odd. For other numbers it prints nothing. The indentation of each line is fixed.

With the reply 7, the program in the right order prints:

Target

positive and odd
  1. print("positive and even")
  2. print("positive and odd")
  3. if number > 0:
  4. if number % 2 == 0:
  5. number = int(input("Number: "))
  6. else:

Fill in the blank

Two nested ifs were flattened into one. Fill in the word, so that the message is shown only when both conditions are true.

years = 25
has_ticket = True
if years >= 18  has_ticket:
    print("Welcome to the concert.")

The finished program prints:

Target

Welcome to the concert.

11.7 Writing good conditions

Everything from Chapter 5 can go after if. A few patterns are worth knowing by name.

Truthiness: "is there anything?"

Any value can be a condition. Empty and zero are falsy; everything else is truthy:

name = ""        # what input() gives when the user just presses Enter
if name:
    print(f"Hello, {name}!")
else:
    print("Hello, stranger!")

Output

Hello, stranger!

if name: reads as "if there is a name". It is the idiomatic way to test for an empty string, and it is the fix for the indexing crash from Chapter 8: check if reply: before using reply[0].

Do not compare with True or False

A Boolean is already a condition. Comparing it with True adds nothing:

Instead of Write
if is_member == True: if is_member:
if is_member == False: if not is_member:
if len(name) > 0: if name:

Ranges, with a chained comparison

hour = 14
if 9 <= hour < 17:
    print("The office is open.")

Output

The office is open.

One of several values, with in

Remember the bug from Chapter 5: if day == "Sat" or "Sun": is always true, because the non-empty string "Sun" is truthy. Each side of or must be a full comparison, or better, use in with the allowed values in brackets → Chapter 30:

day = "Mon"
if day in ("Sat", "Sun"):
    print("Weekend!")
else:
    print("Weekday.")

Output

Weekday.

Is there a value at all?

result = None
if result is None:
    print("No result yet.")

Output

No result yet.

Clean first, then compare

User input needs the cleaning from Chapters 6 and 9 before a comparison can be trusted:

reply = input("Delete the file? (yes/no) ").strip().lower()
if reply in ("yes", "y"):
    print("File deleted.")
else:
    print("Nothing was deleted.")

Output

Delete the file? (yes/no)   YES
File deleted.

Notice the design: anything that is not clearly a yes is treated as a no. For a dangerous action, make the safe outcome the default.

= is not ==

Using one equals sign in a condition is a syntax error in Python, and the message says so:

score = 10
if score = 10:
    print("Perfect")

Output

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

(The := it mentions is the walrus operator from Chapter 4, which assigns and gives back the value, and is allowed inside a condition.)

Quick check

Rewrite each condition more simply: (1) if logged_in == True: (2) if len(cart) == 0: for a string cart (3) if colour == "red" or colour == "blue":

Show the answer

Answer: (1) if logged_in: (2) if not cart: (3) if colour in ("red", "blue"):

Practice 11.7

Predict the output

What does it print?

name = ""
hour = 9
day = "Sun"
if not name:
    print("no name")
if 9 <= hour < 17:
    print("open")
if day == "Sat" or day == "Sun":
    print("weekend")

Multiple choice

What does this program show?

day = "Mon"
if day == "Sat" or "Sun":
    print("Weekend!")
else:
    print("Weekday.")
Choose one answer

Fix the bug

The user types YES (with spaces and capital letters) and the file is not deleted. Fix the program so that a yes in any mix of capitals, with spaces around it, is understood.

With the reply YES , the program prints the lines below. Your program must print exactly these lines.

Example run

File deleted.

11.8 A decision in one line: the conditional expression

A very common shape is "set a variable to one of two values":

age = 20
if age >= 18:
    status = "adult"
else:
    status = "minor"
print(status)

Output

adult

Python has a compact form for exactly this, called a conditional expression:

age = 20
status = "adult" if age >= 18 else "minor"
print(status)

Output

adult

Read it almost as English: status is "adult" if age is at least 18, else "minor".

  value_if_true   if   condition   else   value_if_false

The condition sits in the middle. Python checks it first, then works out only the side it needs.

It is an expression: it produces a value. So it can go anywhere a value can go, including inside an f-string or a function call:

count = 1
print(f"You have {count} new message{'s' if count != 1 else ''}.")
count = 3
print(f"You have {count} new message{'s' if count != 1 else ''}.")
print(max(5, 9) if True else "never")

Output

You have 1 new message.
You have 3 new messages.
9

It always needs both parts. There is no conditional expression without else, because an expression must always have a value.

Practice 11.8

Fill in the blank

Fill in the two keywords of the conditional expression.

marks = 55
result = "pass"  marks >= 40  "fail"
print(result)

The finished program prints:

Target

pass

Predict the output

What does it print?

count = 1
print(f"{count} item{'s' if count != 1 else ''}")
points = 0
print("has points" if points else "no points")
print("big" if 7 > 5 else "small")

Write code

Ticket or tickets. Ask for a whole number of tickets. Print one line with the number, one space and the word: the word is ticket when the number is 1, and tickets for every other number. Choose the word with a conditional expression.

With the reply 1, the program prints the lines below. Your program must print exactly these lines.

Example run

1 ticket

11.9 The variable that might not exist

Here is a trap that catches everyone:

marks = 30
if marks >= 40:
    result = "pass"
print(result)

Output

Traceback (most recent call last):
  File "result.py", line 4, in <module>
    print(result)
          ^^^^^^
NameError: name 'result' is not defined

The name result is only created if the assignment line runs. With marks of 30, the block is skipped, result never comes into existence, and the last line fails. With marks of 50 this program works, which is why such a bug can hide for a long time: it appears only for some inputs.

There are two standard fixes.

Give the variable a starting value before the if:

marks = 30
result = "fail"
if marks >= 40:
    result = "pass"
print(result)

Output

fail

Or make sure every path assigns it, with an else:

marks = 30
if marks >= 40:
    result = "pass"
else:
    result = "fail"
print(result)

Output

fail

Practice 11.9

Multiple choice

What happens when this program is run?

stock = 0
if stock > 0:
    message = "in stock"
print(message)
Choose one answer

Fix the bug

Shipping is free for orders of 50 dollars or more, and costs 4 dollars for smaller orders. This program crashes for small orders. Fix it.

With the reply 20, the program prints the lines below. Your program must print exactly these lines.

Example run

Shipping: 4

Put the lines in order

Put the lines in order. The program asks for the marks on its first line. The result must have a value on every path, also when the marks are below 40.

With the reply 30, the program in the right order prints:

Target

fail
  1. result = "pass"
  2. result = "fail"
  3. if marks >= 40:
  4. marks = int(input("Marks: "))
  5. print(result)

11.10 An empty block: pass

A block must contain at least one statement. Sometimes you have nothing to put there yet, because you are sketching the structure first. The pass statement does nothing at all and exists exactly for this:

temperature = 15
if temperature < 0:
    pass        # TODO: send a frost warning
else:
    print("No frost.")

Output

No frost.

A comment alone is not enough, because comments are ignored and the block would still be empty. pass is a placeholder that keeps the program valid while you build it.

If you find a finished program with if something: pass followed by else:, flip the condition with not and drop the empty branch.

Practice 11.10

Fill in the blank

The frost warning is not written yet. Fill in the statement that does nothing, so that the block is not empty and the program is valid.

temperature = 15
if temperature < 0:
    
else:
    print("No frost.")

The finished program prints:

Target

No frost.

11.11 Patterns you will use again and again

The larger of two values (the built-in max does this, but it is good to see how):

first = 42
second = 17
if first >= second:
    larger = first
else:
    larger = second
print(larger)

Output

42

Validate, then work. Check that the input makes sense before using it:

quantity = int(input("How many tickets? "))
if quantity <= 0:
    print("Please enter a number above zero.")
elif quantity > 10:
    print("Sorry, the limit is 10 tickets per person.")
else:
    print(f"Total: {quantity * 12} dollars")

Output

How many tickets? -5
Please enter a number above zero.

A menu. One block per choice, and an else for anything unexpected:

print("1. Balance  2. Deposit  3. Exit")
choice = input("Choose: ").strip()
if choice == "1":
    print("Your balance is 250 dollars.")
elif choice == "2":
    print("How much would you like to deposit?")
elif choice == "3":
    print("Goodbye.")
else:
    print("Please choose 1, 2 or 3.")

Output

1. Balance  2. Deposit  3. Exit
Choose: 2
How much would you like to deposit?

The choice is compared as text ("1", not 1). There is no need to convert it to a number, and comparing text means a reply such as abc simply falls through to the else without crashing. (Chains like this, which compare one value against several fixed options, can also be written with match → Chapter 12.)

Leap year. Chapter 5 wrote this as one Boolean expression. Here it is as a chain, which many people find easier to check against the rule: every fourth year is a leap year, except century years, except every fourth century.

year = 1900
if year % 400 == 0:
    leap = True
elif year % 100 == 0:
    leap = False
elif year % 4 == 0:
    leap = True
else:
    leap = False
print(year, leap)

Output

1900 False

The most specific rule (divisible by 400) is tested first, exactly as section 11.4 advised.

Practice 11.11

Write code

Leap year. Ask for a year (a whole number). Print leap or not leap. The rule: a year that can be divided by 400 is a leap year; if not, a year that can be divided by 100 is not a leap year; if not, a year that can be divided by 4 is a leap year; every other year is not.

With the reply 1900, the program prints the lines below. Your program must print exactly these lines.

Example run

not leap

11.12 Common mistakes

The mistake What you see The fix
Forgetting the colon SyntaxError: expected ':' End if, elif and else lines with :
Not indenting the block IndentationError: expected an indented block Indent four spaces
A line dedented by accident It always runs, whatever the condition Check each line: inside or outside?
= in a condition SyntaxError ... Maybe you meant '==' Use ==
Conditions in the wrong order The first, loosest condition always wins Most demanding condition first
Separate ifs where a chain is needed Several blocks run Use elif
if day == "Sat" or "Sun": Always true if day in ("Sat", "Sun"):
Comparing input with a number: if choice == 1: Never true, because choice is a str Compare with "1", or convert first
A variable assigned on only one path NameError, but only for some inputs Give it a starting value, or add else
else with a condition: else marks < 40: SyntaxError else takes no condition; use elif
Mixing tabs and spaces TabError Convert indentation to spaces

Practice 11.12

Multiple choice

A chain starts with if marks >= 40:. Three of these lines can start its last branch. Which one is a SyntaxError?

Choose one answer

11.13 Putting it together

11.14 How if works inside Python

+ Practice

Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.

Questions

Check yourself

What two things on the first line make a statement an if, apart from the keyword itself?

Show the answer

A condition, and a colon at the end of the line.

Check yourself

How does Python know which lines belong to an if block?

Show the answer

By indentation. Every line indented under the if by the same amount belongs to its block. The block ends at the first line that returns to the if's own level.

Check yourself

In an if/elif/else chain, how many blocks can run? What decides which?

Show the answer

At most one (exactly one if there is an else). Python runs the block of the first condition that is true and skips all the rest.

Check yourself

Why is the condition marks >= 60 enough in the grade chain, without also writing marks < 75?

Show the answer

Python only reaches that elif if the earlier conditions, >= 90 and >= 75, were false. So the marks are already known to be below 75.

Check yourself

What is the difference between three separate if statements and one if/elif/elif chain?

Show the answer

In a chain, only the first true condition's block runs. With separate ifs, every condition is tested and every true one runs its block.

Check yourself

Does an else have a condition? When does its block run?

Show the answer

No. It runs when none of the conditions above it in the chain were true.

Check yourself

Rewrite if is_open == False: in the recommended style.

Show the answer

if not is_open:

Check yourself

What is wrong with if answer == "y" or "yes":?

Show the answer

It is read as (answer == "y") or ("yes"). The string "yes" is non-empty and therefore truthy, so the condition is always true. Write if answer in ("y", "yes"):.

Check yourself

Write label = "even" if n % 2 == 0 else "odd" as an ordinary if/else.

Show the answer

if n % 2 == 0: then label = "even", else: then label = "odd".

Check yourself

Why can a variable assigned inside an if cause a NameError later? Give two ways to prevent it.

Show the answer

The assignment only happens if that block runs. If it is skipped, the name is never created. Prevent it by assigning a starting value before the if, or by making sure every path assigns it (add an else).

Predict the output

Predict the output

x = 10
if x > 5:
    print("A")
if x > 8:
    print("B")
elif x > 9:
    print("C")
else:
    print("D")
print("E")

Predict the output

speed = 80
if speed > 120:
    print("too fast")
elif speed > 60:
    print("fast")
elif speed > 30:
    print("normal")
print("done")

Predict the output

name = ""
score = 0
if name or score:
    print("one")
if not name and not score:
    print("two")
if name == "" and score is not None:
    print("three")

Predict the output

n = 15
if n % 3 == 0:
    if n % 5 == 0:
        print("both")
    else:
        print("three only")
    print("checked five")
print("end")

Predict the output

stock = 0
message = "in stock" if stock else "sold out"
print(message)
print("yes" if "a" in "cat" else "no", "big" if 3 > 5 else "small")

Fix the bug

Fix the bug

Fix the two syntax problems.

The program prints the lines below. Your program must print exactly these lines.

Example run

Access granted

Fix the bug

Both messages should appear only for negative numbers. For 8, this still prints Negative numbers are not allowed. Why is there no error message, and what is the fix?

This one is not checked automatically. Run your program, then compare it with the book's answer.

Show the book's answer

The second print is not indented, so it is not part of the block. It is an ordinary statement after the if, and it always runs. The program is valid Python, so there is nothing for Python to complain about: this is a logic error. Indent the line.

number = 8
if number < 0:
    print("That is a negative number.")
    print("Negative numbers are not allowed.")
print("checked")

Output

checked

Fix the bug

With 85 marks, this prints Pass when it should print Distinction.

The program prints the lines below. Your program must print exactly these lines.

Example run

Distinction

Fix the bug

This prints Welcome no matter what is typed.

With the reply student, the program prints the lines below. Your program must print exactly these lines.

Example run

Access denied

Fix the bug

This crashes for some ages.

With the reply 30, the program prints the lines below. Your program must print exactly these lines.

Example run

Discount: 0 percent

Fix the bug

The user types 2, but the program prints Unknown option.

With the reply 2, the program prints the lines below. Your program must print exactly these lines.

Example run

Stop

Coding problems

Write code · Easy

Positive, negative or zero. Ask for a number and print which of the three it is.

Print one word only: positive, negative or zero.

With the reply -3.5, the program prints the lines below. Your program must print exactly these lines.

Example run

negative

Write code · Easy

Enough money?. Ask for a price and for the money the customer has. Print either the change they get back or how much more they need.

Ask for the price first, then the money. Print one number: the change, or how much more is needed. Round it to 2 decimal places.

With the replies 14.50 then 20, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Change: 5.5

Write code · Easy

Vowel or not. Ask for a single letter and print whether it is a vowel. Accept capitals and lowercase. If the user types more than one character, or none, say so.

Print exactly one of these lines: vowel, not a vowel or Please type exactly one letter.

With the reply E, the program prints the lines below. Your program must print exactly these lines.

Example run

vowel

Write code · Medium

Largest of three. Ask for three numbers and print the largest, using only if, elif and else (no max). Make sure it works when two or all three are equal.

Print the largest number only.

With the replies 7 then 12 then 12, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Largest: 12.0

Write code · Medium

Triangle type. Ask for three side lengths. If they cannot form a triangle (each side must be less than the sum of the other two), say so. Otherwise print equilateral (all equal), isosceles (exactly two equal) or scalene (all different).

Print exactly one of these lines: These sides cannot form a triangle., equilateral, isosceles or scalene.

With the replies 5 then 5 then 8, the program prints the lines below. Your program must print exactly these lines.

Example run

isosceles

Write code · Medium

Simple calculator. Ask for a number, an operator (+, -, * or /) and another number, and print the result. Refuse to divide by zero, and give a message for an unknown operator.

Convert both numbers with float(). Print only the result, or Cannot divide by zero., or Unknown operator.

With the replies 12 then / then 0, the program prints the lines below. Your program must print exactly these lines.

Example run

Cannot divide by zero.

Write code · Hard

Shipping cost. Shipping costs 5 dollars for parcels up to 1 kg, 9 dollars up to 5 kg, and 15 dollars up to 20 kg. Heavier parcels are not accepted. Express delivery adds 50% to the cost. Orders worth 100 dollars or more get free standard shipping, but still pay the express extra, calculated on the normal cost. Ask for the weight, the order value and whether express is wanted, and print the shipping cost.

Ask for the weight first, then the order value, then express (yes or no). Print the shipping cost as one number.

With the replies 3.2 then 120 then yes, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Shipping cost: 4.5

Write code · Hard

Quadrant. Ask for the x and y coordinates of a point and print where it lies: in quadrant I, II, III or IV, on the x-axis, on the y-axis, or at the origin.

Ask for x first, then y. Print exactly one of: origin, on the x-axis, on the y-axis, quadrant I, quadrant II, quadrant III or quadrant IV.

With the replies -4 then 7, the program prints the lines below. Your program must print exactly these lines.

Example run

quadrant II

Write code · Hard

Next day. Ask for a day and a month as numbers (assume a year that is not a leap year) and print the date of the following day. Remember months have different lengths, and the day after 31 December is 1 January.

Ask for the day first, then the month. Print one line in the form Next day: D/M, where D is the day number and M is the month number.

With the replies 31 then 12, the program prints the lines below. Your program must print exactly these lines.

Example run

Next day: 1/1

More practice

Write code

Traffic light. Ask for the colour of a traffic light. Remove the spaces at both ends of the reply and make it lowercase. Then print stop for red, get ready for yellow, go for green, and unknown colour for every other reply.

With the reply red, the program prints the lines below. Your program must print exactly these lines.

Example run

stop

Chapter project: Car park fee

Project

Work out a parking fee. Write a program that asks three questions, in this order:

  1. the number of hours parked (a whole number)
  2. the vehicle: car or bike
  3. the day of the week, such as monday

Remove the spaces at both ends of replies 2 and 3 and make them lowercase. The rules of the car park:

  • A stay of less than 1 hour or more than 24 hours is not valid. Print That number of hours is not valid. and nothing else.
  • Up to 2 hours costs 3 dollars. More than 2 and up to 6 hours costs 8 dollars. A longer stay costs 15 dollars.
  • A bike gets 2 dollars off.
  • On saturday and sunday, 4 dollars are added.

For a valid stay, print one line: Fee:, the fee as a whole number, and then the word dollar when the fee is exactly 1, or dollars for every other fee. One space separates the three parts.

Before you write code, sort the rules as section 11.13 did: which rules are alternatives (one chain), and which are independent (separate if statements)?

With the replies 2 then Bike then Monday, the program prints the lines below. Your program must print exactly these lines.

Example run

Fee: 1 dollar