livepython.net
CHAPTER 08If Statements
8.1  IF

Python if Statement: Make Decisions in Code

What Is an if Statement?

So far, Python ran every line of your program, top to bottom. With an if statement, a program can decide: run some lines only when a condition is True.

PYTHONedit me
age = 20
if age >= 18:
    print("You can vote.")
print("Thank you!")
OUTPUT
You can vote.
Thank you!

Change age to 15 and run it again. Now You can vote. disappears, but Thank you! still prints.

Remember the diamond in a flowchart from chapter 3? An if is that diamond, written in Python:

  1. Start:
    Start
  2. Decision:
    Is age 18 or more?
    yes
    Show: You can vote.
    no
    Skip it
  3. Input or output:
    Show: Thank you!
  4. End:
    End
Can this person vote?

The condition

The part after if is the condition. It's a question with a True or False answer, like the comparisons from chapter 5: age >= 18, name == "Sunny", price > 100.

  • If it's True, Python runs the lines under the if.
  • If it's False, Python skips them and carries on below.

Think of a door with a guard: the guard asks one question. Answer yes, and you go through the door. Answer no, and you walk on past it.

An if runs its lines only when its condition is True.

your turnPredict the output

What will this print?

score = 40 if score > 50: print("Pass") print("Done")
Your turn! What will this code show on the screen?

Writing an if: Colon and Indentation

An if has three parts, and Python is strict about all of them:

PYTHONedit me
temperature = 35
if temperature > 30:
    print("It's hot today.")
    print("Drink water!")
OUTPUT
It's hot today.
Drink water!
  1. The word if, then the condition: temperature > 30.
  2. A colon : at the end of the line. It means "here comes what to do".
  3. The lines to run, indented: moved right by 4 spaces. This group of lines is called a block.

Every indented line under the if belongs to it. Both print() lines above run only when it's hot.

Forget the colon

PYTHONedit me
temperature = 35
if temperature > 30
    print("Hot")
OUTPUT
SyntaxError: expected ':'

Python tells you exactly what's missing: a :.

Where the block ends

The block ends at the first line that is not indented any more:

PYTHONedit me
raining = False
if raining:
    print("Take an umbrella.")
print("Have a nice day!")
OUTPUT
Have a nice day!

raining is already True or False, so it can be the condition all by itself. No need for raining == True.

Think of indentation as the inside of a box: everything inside the box belongs to the if. The first line outside the box is back in the main program.

if condition: then the indented block. Don't forget the colon.

your turnFill the gap

Complete the if

age = 20 if age >= 18? print("Adult")

It should print: Adult

Which piece makes this code work?
your turnPredict the output

What will this print?

x = 5 if x > 3: print("A") print("B") print("C")
Your turn! What will this code show on the screen?

Indentation Matters

In many languages, spaces at the start of a line don't matter. In Python, they're part of the code: indentation decides which lines belong to which if.

PYTHONedit me
balance = 50
if balance < 100:
    print("Low balance")
    print("Please add money")
print("Goodbye")
OUTPUT
Low balance
Please add money
Goodbye

Move print("Please add money") to the left edge, and it runs every time, even when the balance is high. One space changes the meaning of the program.

The rules

  • Use 4 spaces for each level. That's the Python standard (PEP 8).
  • All lines in a block must line up exactly.
  • Most code editors add the 4 spaces for you when you press Enter after a colon.

Indentation errors

Forget to indent, and Python complains:

PYTHONedit me
if 5 > 3:
print("Yes")
OUTPUT
IndentationError: expected an indented block after 'if' statement on line 1

Indent a line that shouldn't be, and Python complains too:

PYTHONedit me
print("Hi")
    print("there")
OUTPUT
IndentationError: unexpected indent

Why Python does this

Other languages use brackets { } to mark blocks, and people indent anyway to make code readable. Python simply makes the indentation be the structure. The result: Python code always looks tidy.

Think of indentation as a bulleted list inside a list: the inner items are moved right to show they belong to the item above.

Indent the block under an if by 4 spaces, and line up every line in it.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Decisions with User Input

if becomes really useful with input() from chapter 7: the program reacts to what the user types.

PYTHONedit me
age = int(input())
if age >= 18:
    print("You can get a driving licence.")
print(f"Age checked: {age}")
OUTPUT
You can get a driving licence.
Age checked: 21

Type 16 in the Input box and run it again: the first line disappears.

Convert before you compare

input() gives text. Comparing text with a number never works the way you want:

PYTHONedit me
age = input()
print(age == 18)
OUTPUT
False

The text "18" is not the number 18 (chapter 5). So always convert with int() or float() first, then compare.

Text answers

For yes-or-no questions, compare the text directly:

PYTHONedit me
answer = input()
if answer == "yes":
    print("Great, let's start!")
OUTPUT
Great, let's start!

Remember: string comparisons are exact. "Yes" with a capital Y, or "yes " with a space, won't match. You'll learn how to handle that in the Strings chapter.

Think of a vending machine: it waits for your input, checks it, and only gives you a snack when the check passes.

Read the input, convert it if it's a number, then decide with if.

your turnPredict the output

What will this print?

n = int(input()) if n > 10: print("Big") print("End")

The user types: 7

Your turn! What will this code show on the screen?
your turnFix the code

Make it print: Teen when the user types 15

It should print: Teen

The user types: 15

age = input()
if age < 20:
    print("Teen")
This code does not work yet. Fix it, then press Run.
your turnPredict the output

What will this print?

print(f"{10 % 4}")
Your turn! What will this code show on the screen?

Practice: if

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 59.Python Program to Check If a Number Is PositiveEasySolve
  2. 60.Python Program to Apply a Discount on Orders Over 1000EasySolve