>>> Python for Beginners Chapter 06 of 10

Chapter 06 ยท Decisions

Making Decisions

A program that always does the same thing is a machine with one button. Decisions let your program choose different paths depending on the situation.

๐Ÿšฆ
Real-world analogy

"If the light is green, go; otherwise, stop." We make these if/otherwise decisions all day. Code does the same with if and else.

Asking a yes/no question

An if statement runs its block only when a condition is true. The condition uses a comparison:

age = 20
if age >= 18:
    print("You are an adult.")
You are an adult.

Two things to notice: the line ends with a colon :, and the code inside is indented (pushed in with spaces). That indentation is how Python knows what belongs inside the if.

The comparison operators

SymbolMeans
==equal to (note: two equals signs)
!=not equal to
> / <greater than / less than
>= / <=greater or equal / less or equal

if / else โ€” two paths

password = input("Enter password: ")
if password == "open123":
    print("Access granted.")
else:
    print("Access denied.")
Enter password: open123 Access granted.

if / elif / else โ€” many paths

Use elif ("else if") to check several possibilities in order:

score = int(input("Your score: "))
if score >= 75:
    print("Distinction")
elif score >= 50:
    print("Pass")
else:
    print("Try again")
Your score: 62 Pass
โœ๏ธ Try it yourself

Ask the user for a number and print whether it is positive, negative, or zero โ€” using if, elif and else.

= versus ==

= puts a value into a variable. == asks "are these equal?" Using = inside an if is a classic bug. And don't forget the colon and the indentation โ€” Python insists on both.

Recap