temperature=34iftemperature>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=22iftemperature>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:
The if line opens the block and the indented line is the block. The last line is not indented, so it runs every time.
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
The line that opens a block ends with a colon.
Every line of the block is indented by the same amount. The universal convention, from the style guide PEP 8, is four spaces.
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=50price=80ifbalance>=price:
print("Payment accepted.")print("Enjoy your purchase!")
Output
This first program prints nothing at all.
balance=50price=80ifbalance>=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=20ifage>=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=20print("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=20ifage>=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=20ifage>=18print("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")
The if line ends with a colon, so Python expects a block under it.
A block is made of indented lines. Is the print line indented?
The answer is: It stops with an IndentationError
An if must have at least one indented line under it. Without one, Python reports that it expected an indented block.
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.
Output
Ask of each line: is it meant to run only when the condition is true, or always?
A line belongs to the block only when it is indented like the other lines of the block.
balance=int(input("Balance: "))price=80ifbalance>=price:
print("Payment accepted.")print("Enjoy your purchase!")print("Goodbye.")
The indentation decides what is inside the if. A dedented line always runs, and Python gives no error for it.
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: "))ifage>=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.
else gives the path for every case where the condition is false. Exactly one of the two blocks runs.
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
Output
Convert the reply with float(). There are two outcomes, so use if and else.
With if/else exactly one block runs. The boundary value 40 belongs to the first path because the condition uses >=.
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: "))ifmarks>=90:
grade="A"elifmarks>=75:
grade="B"elifmarks>=60:
grade="C"elifmarks>=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:
Test the conditions from the top, one at a time, with 15.
After the first true condition, the rest of the chain is skipped, even when a later condition is also true.
It prints
daytime
done
15 < 12 is false and 15 < 18 is true, so that block runs and the chain ends. 15 < 22 is never checked.
Multiple choice
In one if/elif/else chain, the second and the third condition are both true for some value. Which blocks run?
Python tests the conditions from the top.
The moment one condition is true, Python runs that block and jumps past the rest of the chain.
The answer is: Only the block of the second condition
A chain picks one alternative. The first true condition wins, and later conditions are not even checked.
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.
The first true condition wins. temperature > 0 is true for 120 as well, so the more demanding test >= 100 must come before it.
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=12ifnumber%2==0:
print("divisible by 2")elifnumber%3==0:
print("divisible by 3")elifnumber%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=12ifnumber%2==0:
print("divisible by 2")ifnumber%3==0:
print("divisible by 3")ifnumber%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.
Count the statements: every plain if starts a new, independent question.
The elif belongs to the second if. In that small chain only the first true condition runs.
It prints
two
three
ten
There are three independent statements. The middle one is a chain, so after three its elif is skipped, even though 30 can be divided by 5.
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
Output
The three cases are alternatives: only one can apply to a person.
Join the statements into one chain with elif, so that the first true condition wins.
Separate if statements are independent questions, so several can run. A chain runs at most one block.
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=25has_ticket=Trueifage>=18:
ifhas_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=25has_ticket=Trueifage>=18andhas_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=25has_ticket=Falseifage<18:
print("Sorry, adults only.")elifnothas_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
print("positive and even")
print("positive and odd")
ifnumber>0:
ifnumber%2==0:
number=int(input("Number: "))
else:
The inner if is indented four spaces, so it sits inside the block of the outer if.
An else pairs with the if it lines up with. Each print with eight spaces follows the line that opens its block.
number=int(input("Number: "))ifnumber>0:
ifnumber%2==0:
print("positive and even")else:
print("positive and odd")
The inner if/else is reached only when the outer condition is true. Its two blocks are indented one more level.
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=25has_ticket=Trueifyears>=18has_ticket:
print("Welcome to the concert.")
The finished program prints:
Target
Welcome to the concert.
Which logical operator from Chapter 5 is true only when both sides are true?
Two nested ifs with nothing in between are the same as one if with this word.
years=25has_ticket=Trueifyears>=18andhas_ticket:
print("Welcome to the concert.")
and is true only when both sides are true, which is exactly what two nested ifs test.
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 Enterifname:
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=14if9<=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:
Python reads the condition as (day == "Sat") or ("Sun").
A string that is not empty is truthy.
The answer is: Weekend!
The right side of or is the string "Sun" alone, which is truthy. The condition is true for every day.
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.
Output
Clean first, then compare. Which string method removes the spaces at both ends?
Add .strip().lower() to the reply before the comparison.
reply=input("Delete the file? (yes/no) ").strip().lower()ifreply=="yes":
print("File deleted.")else:
print("Nothing was deleted.")
A comparison with == is exact. Cleaning the reply with strip() and lower() first means the condition only ever sees one form.
11.8 A decision in one line: the conditional expression
A very common shape is "set a variable to one of two values":
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=1print(f"You have {count} new message{'s'ifcount!=1else''}.")count=3print(f"You have {count} new message{'s'ifcount!=1else''}.")print(max(5,9)ifTrueelse"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=55result="pass" marks >= 40 "fail"
print(result)
The finished program prints:
Target
pass
The form is: value when true, a keyword, the condition, a keyword, value when false.
They are the same two keywords as in an ordinary two-path decision.
Find the condition in the middle of each expression first.
1 != 1 is false, and zero is falsy. A false condition picks the value after else.
It prints
1 item
no points
big
A conditional expression gives the value on the left when the condition is true, and the value after else when it is false.
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
Output
Convert the reply with int().
Store the word first: word = ... if count == 1 else .... Then print the number and the word with a comma between them.
A conditional expression chooses between two values in one line. Zero is not 1, so it gets the plural word too.
11.9 The variable that might not exist
Here is a trap that catches everyone:
marks=30ifmarks>=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.
A variable assigned on only one path does not exist on the other path. A starting value, or an else, covers every path.
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
result="pass"
result="fail"
ifmarks>=40:
marks=int(input("Marks: "))
print(result)
The starting value must be given before the if, so that the if can replace it.
The starting value "fail" is stored first. The if replaces it only when the marks are high enough, so the name always exists.
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=15iftemperature<0:
pass# TODO: send a frost warningelse:
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.
Validate, then work. Check that the input makes sense before using it:
quantity=int(input("How many tickets? "))ifquantity<=0:
print("Please enter a number above zero.")elifquantity>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()ifchoice=="1":
print("Your balance is 250 dollars.")elifchoice=="2":
print("How much would you like to deposit?")elifchoice=="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.
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
Output
year % 400 == 0 is true when the year can be divided by 400.
Write one chain and test the most specific rule first: 400, then 100, then 4, then else.
The rules overlap, so the order matters. The most specific rule comes first and each elif relies on the earlier tests having failed.
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?
One of the two keywords never takes a condition.
else means "in every other case", so nothing may stand between else and the colon.
The answer is: else marks < 40:
else takes no condition. A branch that needs a condition must use elif.
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).
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.
Output
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=8ifnumber<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
Output
Python tests the conditions from the top and stops at the first true one. Is 85 >= 40 true?
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
Output
There are two outcomes, so if/else fits. Compare the money with the price.
When the money is enough, print money - price. Otherwise print price - money.
price=float(input("Price: "))money=float(input("Money you have: "))ifmoney>=price:
print("Change:",round(money-price,2))else:
print("You need",round(price-money,2),"more")
price=float(input("Price: "))money=float(input("Money you have: "))ifmoney>=price:
print("Change:",round(money-price,2))else:
print("You need",round(price-money,2),"more")
Output
Price: 14.50
Money you have: 20
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
Output
Clean the reply with .strip().lower(), then check its length first.
letter in "aeiou" is True when the one letter is a vowel.
letter=input("A letter: ").strip().lower()iflen(letter)!=1:
print("Please type exactly one letter.")elifletterin"aeiou":
print("vowel")else:
print("not a vowel")
The length is checked first, so that the rest of the code can rely on having exactly one character.
letter=input("A letter: ").strip().lower()iflen(letter)!=1:
print("Please type exactly one letter.")elifletterin"aeiou":
print("vowel")else:
print("not a vowel")
Output
A letter: E
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
Output
The first number is the largest when it is >= both of the others. Join the two comparisons with and.
When the first is not the largest, only the second and the third are left to compare.
By the time the elif is reached, first is known not to be the largest, so only second and third need comparing.
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
Output
Deal with the impossible case first: one side is greater than or equal to the sum of the other two.
Test "all three equal" before "two equal", because three equal sides also have two equal sides.
x=float(input("Side 1: "))y=float(input("Side 2: "))z=float(input("Side 3: "))ifx>=y+zory>=x+zorz>=x+y:
print("These sides cannot form a triangle.")elifx==y==z:
print("equilateral")elifx==yory==zorx==z:
print("isosceles")else:
print("scalene")
The impossible case is dealt with first. Then "all equal" must be tested before "two equal", because an equilateral triangle also has two equal sides.
x=float(input("Side 1: "))y=float(input("Side 2: "))z=float(input("Side 3: "))ifx>=y+zory>=x+zorz>=x+y:
print("These sides cannot form a triangle.")elifx==y==z:
print("equilateral")elifx==yory==zorx==z:
print("isosceles")else:
print("scalene")
Output
Side 1: 5
Side 2: 5
Side 3: 8
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.
Output
Compare the operator as text, one block per operator, with an else for everything else.
Inside the division block, nest one more if that checks whether the second number is zero.
First number: 12
Operator (+ - * /): /
Second number: 0
Cannot divide by zero.
This is a good use of nesting: the zero check only makes sense inside the division branch.
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
Output
Work out the normal cost from the weight first, with one chain. Keep it in its own variable.
The cost starts at zero for orders of 100 dollars or more, otherwise at the normal cost. Express adds half of the normal cost.
weight=float(input("Weight in kg: "))value=float(input("Order value: "))express=input("Express? (yes/no) ").strip().lower()=="yes"ifweight<=0orweight>20:
print("Sorry, this parcel cannot be shipped.")else:
ifweight<=1:
normal=5elifweight<=5:
normal=9else:
normal=15cost=0ifvalue>=100elsenormalifexpress:
cost=cost+normal*0.5print("Shipping cost:",cost)
Work out the normal cost first, because the express extra is based on it even when standard shipping is free.
weight=float(input("Weight in kg: "))value=float(input("Order value: "))express=input("Express? (yes/no) ").strip().lower()=="yes"ifweight<=0orweight>20:
print("Sorry, this parcel cannot be shipped.")else:
ifweight<=1:
normal=5elifweight<=5:
normal=9else:
normal=15cost=0ifvalue>=100elsenormalifexpress:
cost=cost+normal*0.5print("Shipping cost:",cost)
Output
Weight in kg: 3.2
Order value: 120
Express? (yes/no) yes
Shipping cost: 4.5
A 3.2 kg parcel normally costs 9. The order is worth over 100, so standard shipping is free, and the express extra is half of 9.
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
Output
A point is on the x-axis when its y is zero. After the origin and both axes, no coordinate is zero, so only the signs matter.
deal with the origin and the axes first.
x=float(input("x: "))y=float(input("y: "))ifx==0andy==0:
print("origin")elify==0:
print("on the x-axis")elifx==0:
print("on the y-axis")elifx>0andy>0:
print("quadrant I")elifx<0andy>0:
print("quadrant II")elifx<0andy<0:
print("quadrant III")else:
print("quadrant IV")
x=float(input("x: "))y=float(input("y: "))ifx==0andy==0:
print("origin")elify==0:
print("on the x-axis")elifx==0:
print("on the y-axis")elifx>0andy>0:
print("quadrant I")elifx<0andy>0:
print("quadrant II")elifx<0andy<0:
print("quadrant III")else:
print("quadrant IV")
Output
x: -4
y: 7
quadrant II
After the first three conditions, neither coordinate is zero, so the last else can only mean x positive and y negative.
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
Output
There are three cases for the second decision: an ordinary day, the last day of a month, and the last day of the year.
first work out how many days the month has, using in with groups of months.
The program has two decisions, one after the other: first how long the month is, then which of three things happens (a normal day, the end of a month, the end of the year). Splitting a problem into separate decisions like this keeps each one simple.
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
Output
Clean the reply with .strip().lower() on the line where it arrives.
The colours are alternatives, so use one chain: if, two elif blocks, and an else for anything unexpected.
This is the menu pattern: one block per choice, compared as text, with an else that catches every other reply.
Chapter project: Car park fee
Project
Work out a parking fee. Write a program that asks three questions, in this order:
the number of hours parked (a whole number)
the vehicle: car or bike
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
Output
Check the hours first. Everything else goes in the else block of that check, so the invalid case never reaches the calculation.
The three price bands are alternatives, so they form one chain that sets fee. The bike rule and the weekend rule are independent, so each one is its own if after the chain.
Choose the last word with a conditional expression: unit = "dollar" if fee == 1 else "dollars". Then print the three parts with an f-string or with commas.
hours=int(input("Hours parked: "))vehicle=input("Vehicle (car/bike): ").strip().lower()day=input("Day of the week: ").strip().lower()ifhours<1orhours>24:
print("That number of hours is not valid.")else:
ifhours<=2:
fee=3elifhours<=6:
fee=8else:
fee=15ifvehicle=="bike":
fee=fee-2ifday=="saturday"orday=="sunday":
fee=fee+4unit="dollar"iffee==1else"dollars"print(f"Fee: {fee}{unit}")
Alternatives form one chain and independent rules are separate if statements, as in section 11.13. The problem case is handled first, and a conditional expression picks between the two words.