Python Basics · Lesson 6 of 12

Making Decisions

With if, a program can choose what to do.

temperature = 31

if temperature > 30:
    print("It is hot today.")
    print("Drink some water.")

print("Have a nice day.")

The condition is followed by a colon. The lines that belong to the if are indented by four spaces. They run only when the condition is true. The last line is not indented, so it always runs.

Indentation is the structure

In many languages indentation is only tidiness. In Python it is the grammar: the indented lines form a block. Get the spaces wrong and you get an IndentationError, or worse, a program that runs but does the wrong thing. The editor indents for you after a colon.

Comparisons

OperatorMeaning
> and <greater than, less than
>= and <=greater or equal, less or equal
==equal to
!=not equal to

Two equals signs compare. One equals sign assigns. Writing if x = 5: is an error.

A comparison gives True or False. These two values are called booleans.

elif and else

elif (short for "else if") adds another condition. else catches everything left over. Python checks from the top and runs only the first block whose condition is true:

if temperature > 30:
    print("Hot")
elif temperature > 15:
    print("Nice")
else:
    print("Cold")

Combine conditions with the words and, or and not:

if age >= 13 and age <= 19:
    print("Teenager")

Your Task

  1. Write an if / elif / else chain that sets the variable grade from score:
  2. "A" when the score is 90 or more,
  3. "B" when it is 75 or more,
  4. "C" for anything lower.
  5. Print grade. Then change score at the top to other numbers and run it again to test every branch.
  • The code uses if, elif and else
  • grade is correct for the score at the top of your code
  • The chain gives A for 95, B for 75 and C for 40
  • The grade is printed