Python from zeroBeginnerLesson 1017 min read

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.

Lesson in motion

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.

1/4
In simple words
Every morning you make small decisions: if it is raining, take an umbrella; otherwise, take a cap. A program can make decisions the same way. It checks something, and then picks what to do.

Comparing values

A comparison asks a yes-or-no question. The answer is either True or False. These two values have their own type, called bool (short for Boolean).
SymbolMeansExampleAnswer
==is equal to5 == 5True
!=is not equal to5 != 3True
>is greater than40 > 35True
<is less than20 < 10False
>=is greater than or equal to35 >= 35True
<=is less than or equal to36 <= 35False
Watch out
One = stores a value: marks = 80. Two == compare: marks == 80. Mixing them up is one of the most common beginner mistakes.

if and else

Python: pass or notpython
marks = 42
if marks >= 35:
    print("Passed! Well done.")
else:
    print("Not passed this time. Keep practising.")
print("Result checked.")
Look closely at the shape:
  • The if line ends with a colon :.
  • The lines that belong to the if are 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.
Python: ticket counterpython
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 practice
For age 9, the first test (age < 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

Python: combining conditionspython
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

In the lab you will put your decision inside a small function. A function is a named set of steps that takes a value and gives back an answer. You will learn functions properly in Lesson 6. For now, just follow the shape:
Python: a tiny functionpython
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.
Tricky
  • Forgetting the colon after if marks >= 35
  • Some lines indented with 2 spaces, others with 4
  • Putting if marks >= 35 before if marks >= 90 in an elif chain, so 95 never reaches the top grade
Tidy
  • Every if, elif and else line ends with :
  • Always 4 spaces for each level of indentation
  • Check the highest level first, then work down
Try this. In the ticket counter, set 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.

~12 min

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):

MarksGrade
90 to 100"A"
75 to 89"B"
60 to 74"C"
35 to 59"D"
below 35"Fail"
  1. Press Run to see what the starter gives now. Some answers are wrong.
  2. Add elif lines for B, C and D. Start from the top grade and work down.
  3. 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.

Output

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 &gt;= 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.

Please sign in to continue.

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.

Sign in to take the test and save your progress