Input and conditions: if, elif and else
Make programs interactive with input() and let them decide with if, elif, else, truthy values and match.
In this lesson you will
- Read user input and convert it
- Write if, elif and else
- Combine conditions
- Use truthy values, in and match
About 18 minutes
A program that listens and decides
So far your programs have talked at the user. Real programs also listen, and they make choices. You walk to the door of a cafe: if it is open, you go in; otherwise you walk on. Every day you make hundreds of decisions like that. This lesson teaches Python to ask questions with input() and to choose a path with if, elif and else.
Asking the user: input()
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")
What is your name? Sara
Nice to meet you, Sara!
In the example above, the user typed Sara and pressed Enter. (The output here shows the typed answer after the question so you can follow along.) The text inside input() is the prompt. Whatever the user types comes back as a string, always, even if they type digits.
age_text = input("How old are you? ")
print(type(age_text))
age = int(age_text)
print("Next year you will be", age + 1)
How old are you? 28
<class 'str'>
Next year you will be 29
age = int("twenty")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'twenty'
Converting nonsense raises a ValueError. In a later lesson you will learn to catch such errors politely. For now, remember that input always arrives as text and needs converting before maths.
if, elif, else
hour = 14
if hour < 12:
print("Good morning")
elif hour < 18:
print("Good afternoon")
else:
print("Good evening")
Good afternoon
Read it from the top. Python checks the first condition. If it is True, it runs the indented block beneath it and skips the rest. If not, it moves to the next elif (short for “else if”). The final else catches everything that did not match. Only one block ever runs.
The colon : at the end of the if line and the indentation of the next lines are not optional. They tell Python which lines belong to the decision. Use four spaces.
A grade checker
score = int(input("Enter your score: "))
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "Fail"
print(f"Your grade is {grade}")
Enter your score: 82
Your grade is B
Because Python stops at the first true condition, the order of your checks matters. If you checked score >= 50 first, a score of 95 would get a C.
Combining conditions
age = 17
has_parent = True
if age >= 18 or has_parent:
print("You can enter")
else:
print("Sorry")
temperature = 25
if 20 <= temperature <= 30 and not False:
print("Pleasant weather")
You can enter
Pleasant weather
Truthy and falsy values
Python can treat many values as true or false inside an if. The “empty” values are falsy: False, 0, 0.0, "" (empty text), None, and empty lists, tuples, dictionaries and sets. Everything else is truthy.
username = ""
if username:
print("Welcome", username)
else:
print("Please enter a name")
Please enter a name
Nested conditions
age = 25
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Bring your ID")
else:
print("Too young")
# the same idea, flatter and easier to read
if age >= 18 and has_id:
print("Entry allowed")
Entry allowed
Entry allowed
Nesting works, but deep nesting gets hard to read. Often and flattens it, or you can handle the problem cases first and exit early.
A conditional expression (one-line if)
age = 20
status = "adult" if age >= 18 else "minor"
print(status)
n = 3
print(f"You have {n} item" + ("" if n == 1 else "s"))
adult
You have 3 items
Checking membership with in
fruit = "mango"
if fruit in ["apple", "banana", "mango"]:
print("We sell that")
if "@" not in "sara.example.com":
print("That is not an email address")
We sell that
That is not an email address
match: many exact choices
day = "Sat"
match day:
case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
print("Work day")
case "Sat" | "Sun":
print("Weekend")
case _:
print("Unknown day")
Weekend
match compares one value against several patterns. The underscore _ is the catch-all, like else. For a few choices, plain if/elif is just as good.
A complete little program
print("Ticket price calculator")
age = int(input("Age: "))
is_member = input("Member? (yes/no): ").lower() == "yes"
if age < 5:
price = 0
elif age < 18:
price = 200
elif age >= 60:
price = 250
else:
price = 500
if is_member:
price = price * 0.8
print(f"Your ticket costs Rs {price:.0f}")
Ticket price calculator
Age: 30
Member? (yes/no): Yes
Your ticket costs Rs 400
Ask for a number and say whether it is positive, negative or zero. Test it with -4.
Show one possible answer
n = int(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Enter a number: -4
Negative
A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400. Check 2100 and print the result.
Hint: Combine conditions with and, or and brackets.
Show one possible answer
year = 2100
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
2100 is not a leap year
Using = instead of == in a condition, forgetting the colon at the end of the if line, or indenting with a mix of tabs and spaces. Python reports SyntaxError or IndentationError; check those three first.
If you can state a rule in plain words (“free over 2000, cheaper for members, standard otherwise”), you can write it as if / elif / else. Plan in words, then translate.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What type does input() always return?
- int
- float
- str
- bool
Input is always text; convert it if you need a number.
How many blocks run in an if / elif / else chain?
- Exactly one
- All of them
- Two
- None
Only the first matching block runs.
Which value is falsy?
"0"""(empty string)[0]"False"
Empty text is falsy; non-empty text is truthy.
What must end an if line?
- A semicolon
- A bracket
- Nothing
- A colon
The colon introduces the indented block.
What does "adult" if age >= 18 else "minor" do?
- Prints twice
- Chooses one of two values
- Loops
- Causes an error
It is a one-line conditional expression.
Summary
- input() returns text.
- if / elif / else runs exactly one block.
- Indentation and the colon define the block.
- Empty values are falsy.
Questions
What if the user types letters where I expect a number?
int() raises a ValueError. You will learn to catch it with try/except in the error handling lesson.
Can I have an if without an else?
Yes. else and elif are optional.
Should I use match or if/elif?
match is neat for many exact choices. if/elif is more flexible for ranges and conditions.
