Python Basics for Absolute BeginnersLesson 3 of 59 min read

Python Decisions and Loops: if, for, while

Make decisions with if, elif and else, compare values, and repeat code with for, range() and while loops.

So far your programs run every line from top to bottom, once. Real programs need to choose (“if the password is right, let them in”) and repeat (“ask again until they type a number”). In this lesson you’ll learn both: if statements for decisions and for and while loops for repetition.

Comparisons: True or False

A comparison produces a boolean value, either True or False:

>>> 5 > 3
True
>>> 2 == 3
False
>>> "cat" != "dog"
True
Operator Meaning
== equal to
!= not equal to
> / < greater / less than
>= / <= greater / less than or equal

Notice the difference: a single = sets a variable, a double == compares two values. Mixing them up is one of the most common beginner mistakes.

You can combine comparisons with and, or and not. For example, age >= 13 and age <= 19 is True only for teenagers.

if, elif, else

An if statement runs a block of code only when a condition is True:

temperature = int(input("Temperature in °C: "))

if temperature >= 30:
    print("It's hot. Drink water!")
elif temperature >= 15:
    print("Nice weather.")
else:
    print("Bring a jacket.")

Python checks the conditions in order and runs only the first block whose condition is true. If none are true, it runs the else block. elif (short for “else if”) and else are optional.

Indentation matters. The lines inside each block must be indented, usually by four spaces. Python uses indentation to know which lines belong to the if. The colon : at the end of the if line is required too. Forgetting either gives an error such as IndentationError or SyntaxError.

for loops: repeat for each item

A for loop repeats a block once for each item in a sequence. The simplest sequence is range():

for i in range(5):
    print("Lap", i)
Lap 0
Lap 1
Lap 2
Lap 3
Lap 4

range(5) produces the numbers 0, 1, 2, 3 and 4. It starts at 0 and stops before the number you give it. You can also give a start: range(1, 6) gives 1 to 5.

Loops can also go through the characters of a string:

for letter in "hey":
    print(letter.upper())

This prints H, E and Y on separate lines.

A common pattern is accumulating a total:

total = 0
for n in range(1, 11):
    total = total + n
print(total)   # 55

while loops: repeat until something changes

A while loop repeats as long as its condition stays True. It’s useful when you don’t know in advance how many times to repeat:

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Lift off!")

Make sure something inside the loop eventually makes the condition False. Otherwise you get an infinite loop. If that happens, press Ctrl+C to stop the program.

Practice: ask until the input is valid

In Lesson 2, int(input()) crashed if the user typed letters. Here’s a safer version using a while loop and the string method .isdigit(), which returns True if a string contains only digits:

answer = input("Pick a number from 1 to 10: ")
while not answer.isdigit() or not (1 <= int(answer) <= 10):
    answer = input("Please type a whole number from 1 to 10: ")

number = int(answer)
print(f"You picked {number}.")

The loop keeps asking until the input is valid, then the program continues. (Python also has try/except for handling errors, which you’ll meet as you go further.)

Practice: a guessing game

secret = 7
guess = 0
tries = 0

while guess != secret:
    guess = int(input("Guess the number (1-10): "))
    tries = tries + 1
    if guess < secret:
        print("Too low.")
    elif guess > secret:
        print("Too high.")

print(f"Correct! You got it in {tries} tries.")

Try changing the secret number, or limiting the player to three tries.

Key takeaways

  • Comparisons like ==, != and > produce True or False; = sets, == compares.
  • if, elif and else run only the first matching block. Colons and indentation are required.
  • for loops repeat once per item; range(5) gives 0 to 4.
  • while loops repeat until their condition becomes False. Make sure it eventually does.

Source checked: the official Python Tutorial, “More Control Flow Tools”.

In Lesson 4 you’ll store many values in lists and package code into reusable functions.

Progress is saved in this browser only.