Python · Beginner · 10 min
Making decisions
Choose between two actions with if and else.
Run code when a condition is true
An if statement checks a condition. End its first line with a colon and indent the code below it. Use four spaces consistently for this lesson.
temperature = 12
if temperature < 15:
print("Take a jacket")Output
Take a jacket
Choose the other action
An else block runs when the if condition is false. Keep else aligned with if. Only one of these two blocks runs.
stock = 0
if stock > 0:
print("Available")
else:
print("Sold out")Output
Sold out
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Choose a delivery message
Keep total as 25. If it is at least 20, store Free delivery in message; otherwise store Delivery fee. Display message.
Write an if and an else, then print the message after both blocks.
Try a different example independently
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Choose the cheaper offer
With the percentage discount, a jacket costs $36. With the fixed discount, it costs $35. Use if and else to store the lower of percent_price and fixed_price in best_price, then print it.
Use < to compare the prices. Assign one price to best_price in each block, then print it after if and else.
Making decisions
- Mark the block selected by each condition.
- Check the colons and indentation.