Making decisions with if
Programs become useful when they can choose. Learn to compare values and use if, elif and else to do different things in different cases.
In 60 seconds
Making decisions with if
Programs become useful when they can choose. Learn to compare values and use if, elif and else to do different things in different cases.
Comparing values
True or False. These two values have their own type, called bool (short for Boolean).| Symbol | Means | Example | Answer |
|---|---|---|---|
== | is equal to | 5 == 5 | True |
!= | is not equal to | 5 != 3 | True |
> | is greater than | 40 > 35 | True |
< | is less than | 20 < 10 | False |
>= | is greater than or equal to | 35 >= 35 | True |
<= | is less than or equal to | 36 <= 35 | False |
= stores a value: marks = 80. Two == compare: marks == 80. Mixing them up is one of the most common beginner mistakes.if and else
marks = 42
if marks >= 35:
print("Passed! Well done.")
else:
print("Not passed this time. Keep practising.")
print("Result checked.")- The
ifline ends with a colon:. - The lines that belong to the
ifare pushed in with 4 spaces. This is called indentation, and in Python it is required, not just for looks. else:means "in every other case". It has no condition of its own.- The last line is not indented, so it runs every time, whatever the marks.
Many choices with elif
elif is short for "else if". Python checks each condition from top to bottom and runs only the first one that is True. Then it skips the rest.age = 9
if age < 5:
ticket = "free"
elif age < 12:
ticket = "child"
else:
ticket = "adult"
print(f"Age {age}: {ticket} ticket") # made-up rules, just for practiceage < 5) is False, the second (age < 12) is True, so the ticket is "child" and Python never looks at else. The order of the tests matters.Joining conditions: and, or, not
temperature = 34
has_water = True
if temperature > 30 and has_water:
print("Hot day, but you have water. Good.")
if temperature > 30 or temperature < 10:
print("Extreme weather today.")
if not has_water:
print("Please carry a bottle.")A first look at functions
def ticket_type(age):
if age < 12:
return "child"
else:
return "adult"
print(ticket_type(8))
print(ticket_type(30))def starts the function. age is the value it receives. return hands the answer back. You can then use the function again and again with different ages.- Forgetting the colon after
if marks >= 35 - Some lines indented with 2 spaces, others with 4
- Putting
if marks >= 35beforeif marks >= 90in an elif chain, so 95 never reaches the top grade
- Every
if,elifandelseline ends with: - Always 4 spaces for each level of indentation
- Check the highest level first, then work down
age = 12. Which ticket do you get? Is that what the rule should say? Changing < to <= changes who counts as a child.Watch and read more
Lab
A grade(marks) function that turns exam marks into a grade.
The problem
Finish the function grade(marks) so it returns the right grade for marks out of 100, using these rules (made up for this lab):
| Marks | Grade |
|---|---|
| 90 to 100 | "A" |
| 75 to 89 | "B" |
| 60 to 74 | "C" |
| 35 to 59 | "D" |
| below 35 | "Fail" |
- Press Run to see what the starter gives now. Some answers are wrong.
- Add
eliflines for B, C and D. Start from the top grade and work down. - Test the edges: 90, 89, 75, 74, 60, 59, 35 and 34. Edges are where bugs hide.
Press Check when every line looks right.
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Why does the order of the elif tests matter? Show what goes wrong if <code>marks >= 35</code> comes first.Reveal
Python runs only the first True branch. If the first test is marks >= 35, then 95 passes it and gets "D", and the A, B and C tests are never reached. Checking the highest level first makes each later test mean "between this and the one above".
Q2What should a careful grade function do with marks of 105 or -3, and how could you add that?Reveal
Those marks are impossible for a test out of 100, so it is safer to flag them than to give a grade. You could add a first test such as if marks < 0 or marks > 100: return "Invalid". Catching bad input early is a good habit in all programs.
Questions people ask
Do I always need an else?
No. An if on its own is fine when you only want to do something in one case. Add else when you also want to do something in every other case.
Why does Python care so much about spaces?
Python uses indentation to know which lines belong to the if. Other languages use curly brackets for this. Four spaces is the usual style. Many code editors add them for you when you press Tab.
Can I compare text?
Yes. "Delhi" == "Delhi" is True, but "delhi" == "Delhi" is False, because capitals matter. A common trick is to compare lower-case versions: city.lower() == "delhi".
What is the difference between several ifs and an if-elif chain?
Separate if statements are each checked, so more than one can run. In an if/elif/else chain, only the first True branch runs. For grades, you want exactly one answer, so a chain is right.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.