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.
if — “if this is true…”
Section titled “if — “if this is true…””Inputs (for input())
One value per line — read in order by input().
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
printhas 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?
Indentation — Python’s golden rule
Section titled “Indentation — Python’s golden rule”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.
else — “otherwise…”
Section titled “else — “otherwise…””What should happen when the condition isn’t true? else handles that:
Inputs (for input())
One value per line — read in order by input().
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. 🙂
Missions
Section titled “Missions”Door guard
+10 XP ✓ CompletedBuild 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().
Negative or positive?
+10 XP ✓ CompletedHave 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().
Movie ticket
+15 XP ✓ CompletedCinema 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().
Next lesson: all of the comparison operators and elif — choosing between more than two paths. Continue →