Skip to content

if — making a choice

So far, every line in your programs ran in order, no questions asked. But real programs make decisions: if the password is correct — open the door, if it’s wrong — keep it shut. In games, “right answer / wrong answer” is exactly this.

Inputs (for input())

One value per line — read in order by input().

Output
 

Let’s read it line by line:

  • if age >= 13:“if age is greater than or equal to 13”. The colon : at the end is required.
  • print(...) — the line that runs when the condition is true. Notice: there are 4 spaces at the start of the line!
  • The last print has no indentation — it doesn’t depend on the condition, so it always runs.

Replace age = 14 with age = 10 and run it again. What changed?

Those 4 spaces aren’t decoration. Python uses indentation to know which lines belong to the condition: indented lines are “inside” the condition, un-indented ones are “outside” it. If you forget the indentation or make it uneven, Python will throw an error. The rule is simple: every line inside a condition is indented 4 spaces.

What should happen when the condition isn’t true? else handles that:

Inputs (for input())

One value per line — read in order by input().

Output
 

One important detail: to compare, you write two equals signs — ==. A single = is assignment (put it in the box), while == is a question (are these equal?). Mixing these up is the number 1 mistake for beginners. 🙂

Mission

Door guard

+10 XP

Build a password checker: if the password is python123, say Door unlocked!, otherwise say Wrong password!. (The correct password is ready in the inputs.)

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Negative or positive?

+10 XP

Have the program read a number: if it’s less than zero, print negative, otherwise print positive or zero. (The input is -5.)

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Movie ticket

+15 XP

Cinema program: if the age is 16 or up, say Enjoy the movie!, otherwise say This film is for adults. (The input is 14 — which answer should come out?)

Inputs (for input())

One value per line — read in order by input().

Output
 

Next lesson: all of the comparison operators and elif — choosing between more than two paths. Continue →