Chapter 4

Decisions and Boolean Logic

A useful program often has to choose what to do next. Conditionals are what let it take one path instead of another.

Chapter 4, Decisions and Boolean Logic

What you will learn

  • Use if, elif, and else.
  • Compare values with relational operators.
  • Combine conditions using and, or, and not.
  • Avoid common comparison and indentation mistakes.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

4.1 True and False

Type this into a file, predict the output, then run it.

Python
temperature = 18
print(temperature < 20)
print(temperature == 18)
print(temperature != 18)

TPRM Lab 4.1: A Simple Decision

Type this into a file, predict the output, then run it.

Python
age = int(input("Age: "))

if age >= 18:
    print("Adult")
else:
    print("Minor")

4.2 More Than Two Paths: elif

Type this into a file, predict the output, then run it.

Python
temperature = 31

if temperature >= 30:
    print("Hot")
elif temperature >= 20:
    print("Warm")
elif temperature >= 10:
    print("Cool")
else:
    print("Cold")

4.3 Multiple Conditions

Type this into a file, predict the output, then run it.

Python
score = 84
attendance = 92

if score >= 80 and attendance >= 90:
    print("Distinction")
else:
    print("Standard result")

TPRM Lab 4.3: Password Length Check

Type this into a file, predict the output, then run it.

Python
password = input("Choose a password: ")

if len(password) >= 8:
    print("Length accepted")
else:
    print("Use at least 8 characters")

Back to Python the TPRM Way