Making decisions with if¶
Goal: make a program do different things depending on a condition.
Why this matters¶
Every program you have written so far runs the same lines from top to bottom, every time. Real programs make choices: if the password is right, log in; if the score is high enough, show "You win". This lesson teaches Python how to choose.
Asking yes-or-no questions¶
Before a program can decide anything, it needs to ask a question with a yes-or-no answer. In Python you do that with comparison operators:
age = 18
print(age == 18)
print(age != 18)
print(age > 21)
print(age < 21)
print(age >= 18)
print(age <= 17)
| Operator | Meaning |
|---|---|
== |
is equal to |
!= |
is not equal to |
> |
greater than |
< |
less than |
>= |
greater than or equal to |
<= |
less than or equal to |
Every comparison produces one of two special values: True or False. These are called booleans,
and they are the third kind of value you have met, after strings and numbers. Note the capital letters:
True and False, not true and false.
One equals sign or two?
= assigns a value: age = 18 means "let age be 18".
== compares two values: age == 18 asks "is age equal to 18?".
Mixing them up is the most common beginner mistake in this lesson.
Comparisons work on strings too. "apple" == "apple" is True, and "Apple" == "apple" is False,
because Python compares text exactly, including capital letters.
The if statement¶
Now the decision itself. An if statement runs a block of code only when a condition is True:
temperature = 31
if temperature > 30:
print("It is hot today.")
print("Drink plenty of water.")
print("Have a nice day.")
Change temperature to 25 and run it again. Now only the last line prints.
Let's take the if line apart:
ifstarts the statement.temperature > 30is the condition. It must be something that isTrueorFalse.- The colon
:at the end says "the block starts on the next line". - The two indented lines are the block. They belong to the
if, and they run only when the condition isTrue. print("Have a nice day.")is not indented, so it is not part of the block. It runs no matter what.
Indentation is not optional¶
In many languages, indentation is just for looks. In Python, indentation is how Python knows which lines belong to which block.
The standard is four spaces per level. Your editor will add them automatically after you type a line ending in :.
This is the first time indentation has mattered, and it will matter for the rest of your Python life.
Loops, functions, and classes all use the same rule: a line ending in :, then an indented block.
Doing something else¶
Often you want one thing to happen if the condition is True and a different thing otherwise. That is else:
age = int(input("How old are you? "))
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
else has no condition of its own. It simply means "in every other case". Exactly one of the two blocks runs, never both, never neither.
More than two choices¶
For several possibilities in a row, add elif branches. The word is short for "else if":
temperature = int(input("Temperature in Celsius: "))
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Warm")
elif temperature > 10:
print("Cool")
else:
print("Cold")
Python checks the conditions from top to bottom and runs the block of the first one that is True.
Then it skips all the rest. With 24 degrees, temperature > 30 is False, so Python moves on;
temperature > 20 is True, so "Warm" prints and the remaining branches are ignored.
That "first match wins" rule is why the order matters. If you put temperature > 10 first, then 24 degrees
would print "Cool", because 24 is greater than 10 and Python would stop looking there.
You can have as many elif branches as you like. The else at the end is optional, but it is a good habit,
because it catches anything you did not think of.
Combining conditions¶
Sometimes one comparison is not enough. Python has three words for combining them:
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome to the show.")
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend.")
raining = False
if not raining:
print("No umbrella needed.")
| Word | Result is True when |
|---|---|
a and b |
both a and b are True |
a or b |
at least one of a or b is True |
not a |
a is False |
Notice the variable has_ticket = True. A variable can hold a boolean directly, and you can use it as a condition on its own.
if has_ticket: reads naturally and means the same as if has_ticket == True:.
A common trap with or
Beginners often write if day == "Saturday" or "Sunday":. It looks right and it does not crash,
but it is always True, because Python reads it as (day == "Saturday") or ("Sunday"), and any non-empty
string counts as True. You must repeat the comparison: day == "Saturday" or day == "Sunday".
Try it¶
Write a program that asks for a number and prints "positive", "negative", or "zero". Test all three cases.
Common mistakes¶
SyntaxError: invalid syntax, pointing at the if line
Usually a missing colon at the end of the line, or a single = where you meant ==.
Newer Python versions say so directly: "Maybe you meant '==' or ':=' instead of '='?"
IndentationError: expected an indented block
The line after if ...: is not indented. Add four spaces at the start of every line that belongs to the block.
IndentationError: unindent does not match any outer indentation level
The lines in a block are indented by different amounts, or you mixed tabs and spaces. Make every line in the block start with exactly the same number of spaces.
The else runs when it shouldn't
Check whether you are comparing a number with a string. input() gives a string, so age >= 18 will crash
and age == 18 will quietly be False until you convert with int().
Exercises¶
- Even or odd. Ask for a whole number and print whether it is even or odd. The
%operator from the last lesson is what you need. - Letter grade. Ask for a score from 0 to 100 and print a grade: 90 or above is A, 80 or above is B, 70 or above is C, 60 or above is D, anything lower is F.
- Login check. Ask for a username and a password. Print a welcome message only if both match values you chose in the program. Otherwise print "Wrong username or password."
Solution 1
Solution 2
score = int(input("Score out of 100: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Because Python stops at the first True condition, elif score >= 80 only runs for scores below 90.
You do not need to write score >= 80 and score < 90.
Solution 3
username = input("Username: ")
password = input("Password: ")
if username == "ada" and password == "engine1843":
print("Welcome back, Ada.")
else:
print("Wrong username or password.")
Real programs never store passwords in plain text like this. It is fine for practice, and you will learn the right way later.
Summary¶
- Comparisons like
==,!=,<,>=produce a boolean:TrueorFalse. =assigns,==compares.if condition:runs an indented block only when the condition isTrue.elifadds more conditions,elsecatches everything left over. The firstTruebranch wins.- Indentation defines blocks. Use four spaces.
and,or, andnotcombine conditions. Repeat the comparison on both sides ofor.
Module 1 complete¶
You can now print, store values, take input, do math, and make decisions. That is enough to write real, if small, programs. Module 2 makes you comfortable with text before Module 3 introduces loops.