All lessons

Making decisions · step 9 of 22

If, else — letting your code decide

9 minRun a block of code only when a condition is true.

Making a decision

An if statement runs a block of code only when its condition is true. The condition ends with a colon, and the block underneath is indented — Python uses that indentation to know what belongs to the if.

temperature = 31
if temperature > 28:
    print("Hot")
else:
    print("Mild")

else catches every other case. Four spaces is the convention for one indent level, and it must be consistent.

What can be a condition?

Anything that produces True or False: the comparison operators ==, !=, >, <, >=, <=, plus the words and, or and not.

The classic first error

Forgetting the colon or the indent gets you a SyntaxError or IndentationError pointing at the line. Both are easy to fix once you know to look for them.

Remember this

  • if runs a block only when the condition is true
  • The block must be indented, with a colon after the condition
  • else handles everything else

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. Which line is a valid if statement?

  2. 2. What does else do?

  3. 3. How does Python know which lines belong to the if block?

Answer all three to check them.

Now write it yourself

0/2 passed
1

Practice 1

`temperature` is set for you. Print `Hot` when it is above 28, otherwise print `Mild`.

practice_1.py

Given for you

temperature = 31
2

Practice 2

`password` is set for you. Print `Access granted` when it equals `buildher123`, otherwise print `Try again`.

practice_2.py

Given for you

password = "buildher123"

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.