Conditions at work
A block can hold any code: calculations, assignments and prints. A common pattern changes a variable only in some cases, and then carries on with whatever the variable holds:
price = float(input("Price: "))
if price > 100:
price = price * 0.9
print("You get a 10% discount.")
print(f"To pay: {price}")
150Price: 150
You get a 10% discount.
To pay: 135.0With a price of 80, the block is skipped, price stays 80.0, and the program prints just To pay: 80.0 after the input.
Several ifs in a row
Each if is checked on its own, so when several conditions are true, several blocks run:
height = int(input("Height in cm: "))
if height >= 100:
print("You can ride the carousel.")
if height >= 120:
print("You can ride the bumper cars.")
if height >= 140:
print("You can ride the roller coaster.")
print("Have fun!")
125Height in cm: 125
You can ride the carousel.
You can ride the bumper cars.
Have fun!When one block changes what the next one checks
The if statements run in order, and a later condition sees the variables as the earlier blocks left them. That can catch you out. At this café, an order of 8 or more gets 2 off, and an order of 10 or more also comes with a free cookie. The program looks right, but try it with an order of 11:
total = int(input("Order total: "))
if total >= 8:
total = total - 2
if total >= 10:
print("A free cookie comes with your order.")
print(f"To pay: {total}")
11Order total: 11
To pay: 9The order was 11, so the customer should get the cookie. But the first block has already lowered total to 9, and the second condition checks that new value. One fix is to keep the price after the discount in a variable of its own, so every condition checks the order as the customer made it:
total = int(input("Order total: "))
to_pay = total
if total >= 8:
to_pay = total - 2
if total >= 10:
print("A free cookie comes with your order.")
print(f"To pay: {to_pay}")
11Order total: 11
A free cookie comes with your order.
To pay: 9Swapping the two if statements would fix this program too. The variable of its own is the safer habit: every check later in the program still sees the order the customer made.