🔀 Making Decisions, lesson 2 of 5
if and else
Run code only when a condition is true, and choose between two paths.
10 min
2 exercises
1 quiz
0/3 solved
Getting Python ready… examples can run in a moment.
An if statement runs a block of code only when its
condition is True:
if condition:
do_this()
Two details matter: the line ends with a colon
:, and the block below is indented (4 spaces
is the convention). Every indented line belongs to the
if; the first line that isn't indented runs no
matter what.
A simple if
Change the temperature to 20. Which lines still print?
What does this print?
Add an else block for what should happen when the
condition is False. Exactly one of the two blocks
runs, never both.
Two paths
One line per input() call
Try a few numbers in the Input box, including 0 and negative numbers.
Ticket price
Children under 12 pay 5, everyone else pays 10.
Use if/else to set price based on age.
Secret door
If the password typed is open sesame, print
Welcome!, otherwise print Access denied.
Your program receives this input: open sesame