So far your programs ran every line in order. Real programs have to choose: if the marks are high enough, give a pass; if the customer is a member, give a discount; if the file is missing, show a message. In Python, choices are written with if, elif and else, using conditions that are either true or false.
Booleans and comparisons
A boolean has only two values: True and False. You usually get one by comparing things. The comparison operators are == (equal), != (not equal), <, >, <= and >=. Remember: one equals sign stores, two equals signs compare. You can join conditions with and, or and not. and needs both sides true. or needs at least one. not flips the result.
if, elif and else
Read the program below. The block under each if is indented by four spaces. That indentation is how Python knows which lines belong to that choice. The colon at the end of the if line is required.
def grade(marks):
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
elif marks >= 50:
return "C"
else:
return "Fail"
for m in [95, 80, 50, 49]:
print(m, grade(m))
age = 17
has_id = True
if age >= 18 and has_id:
print("Can enter")
else:
print("Cannot enter")
# Empty things count as False
name = ""
if not name:
print("Please enter a name")
# Comparison pitfalls
print(5 == 5.0)
print("5" == 5)
print(1 < 5 < 10)
95 A
80 B
50 C
49 Fail
Cannot enter
Please enter a name
True
False
True
- Python checks the conditions from the top. The first one that is true runs, and the rest are skipped. That is why the
gradefunction can check>= 90first and then>= 75: a mark of 80 fails the first and passes the second. elifis short for *else if*. You can have as many as you like, or none.elsehas no condition. It runs when nothing above was true.- A function that returns a value stops at the first
return. Thegradefunction uses that, so it does not need extraelseblocks.
Truthy and falsy
Python lets you use almost any value as a condition. These count as false: False, None (nothing), 0, 0.0, the empty text "", the empty list [], the empty dictionary {} and the empty set. Everything else counts as true. That is why if not name: is a neat way to say: if the name is empty. It makes checks shorter, but it can hide mistakes when 0 is a valid value, so use if x is None when you mean specifically nothing.
Comparison traps
5 == 5.0isTrue, because numbers are compared by value."5" == 5isFalse. Text and number are different kinds of value, and Python does not convert for you. This is why you convertinput()first.1 < 5 < 10isTrue. Python allows chained comparisons, which read like maths.- Compare text with care:
"apple" == "Apple"isFalse. Use.lower()on both sides when case should not matter. - Never compare with
== True. Writeif is_member:instead.
A real example: a discount rule
Suppose a shop gives 10 percent off if the total is at least 1000, and an extra 5 percent for members. Think about the order and write the rule with plain words first. Then turn it into code.
total = 1500
is_member = True
discount = 0
if total >= 1000:
discount = 0.10
if is_member:
discount += 0.05
final = total * (1 - discount)
print(f"Discount {discount:.0%}, pay {final:.2f}")
This prints Discount 15%, pay 1275.00. Notice the nested if: the member check is inside the first block, so it only runs for orders of 1000 or more. If you wrote the member discount for everyone, the result would be different. Always test the edges: exactly 1000, just below it, a member and a non-member.
Testing your decisions
A good habit is to test each branch of your if with values on both sides of the limit. For the grade function the edges are 90, 89, 75, 74, 50 and 49. The sample program tested 95, 80, 50 and 49. If a decision matters, for example about money, write down the cases and check each one.
Your task
- Write
age_check.py. Ask for an age, convert it to a number and printchildfor under 13,teenagerfor 13 to 17,adultfor 18 to 64 andseniorfor 65 and above. - Add a rule: if the age is below 0 or above 120, print
Please check the ageand do nothing else. - Test the edge ages 12, 13, 17, 18, 64 and 65.
- Rewrite your checks with a chained comparison, such as
13 <= age <= 17.
How to check it worked
- Ages 12, 13, 17, 18, 64 and 65 give child, teenager, teenager, adult, adult and senior.
- An age of 150 prints the warning only.
- You can explain why the order of
eliflines matters.