// python · beginner

If Statements and Loops in Python: A Beginner's Guide

Make your Python programs take decisions with if, elif and else, and repeat work with for and while loops. Includes a number-guessing game to build.

So far your programs run from top to bottom, one line after another. Real programs need to make decisions (“is the password correct?”) and repeat work (“do this for every item in the list”). Those two ideas, conditions and loops, are what turn a script into something genuinely useful.

Comparing values

A condition is a question with a True or False answer. You build them with comparison operators:

Operator Meaning Example Result
== equal to 5 == 5 True
!= not equal to 5 != 3 True
> / < greater / less than 7 > 10 False
>= / <= greater / less or equal 3 <= 3 True

Don’t confuse == (“is it equal?”) with = (“set it to”). Mixing them up is one of the most common beginner bugs.

if, elif and else

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

if temperature >= 25:
    print("It's hot. Drink some water!")
elif temperature >= 15:
    print("Nice and mild.")
else:
    print("Grab a jacket.")

How it works:

  1. Python checks the if condition. If it’s True, it runs the indented lines below it and skips the rest.
  2. If not, it tries each elif (else if) in order.
  3. If nothing matched, the else block runs.

The colon at the end of each line and the indentation (four spaces) are required. Indentation is how Python knows which lines belong to which block.

You can combine conditions with and, or and not:

python
age = 16
has_ticket = True

if age >= 12 and has_ticket:
    print("Enjoy the film!")

for loops: repeat a set number of times

A for loop runs once for each item in a sequence. range() gives you a sequence of numbers:

python
for i in range(1, 6):
    print(f"Lap {i}")
output
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5

Notice that range(1, 6) stops before 6. That catches everyone out at first. range(5) on its own counts 0, 1, 2, 3, 4.

You can loop over a string or a list directly, too:

python
topics = ["variables", "loops", "functions"]
for topic in topics:
    print(f"Today I'm learning {topic}")

while loops: repeat until something changes

A while loop keeps going as long as its condition is True. Use it when you don’t know in advance how many times you’ll need to repeat:

python
password = ""
while password != "letmein":
    password = input("Password: ")
print("Access granted.")

Watch out: if the condition never becomes False, the loop runs forever. If your program seems frozen, press Ctrl + C in the terminal to stop it, then check that something inside the loop changes the condition.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this pass and jumps to the next one.
python
for n in range(1, 11):
    if n % 2 == 0:
        continue          # skip even numbers
    if n > 7:
        break             # stop completely after 7
    print(n)
# prints 1, 3, 5, 7

The % operator gives the remainder of a division, so n % 2 == 0 is a neat way to test for even numbers.

Mini project: guess the number

This small game uses everything from this guide:

python
import random

secret = random.randint(1, 20)
attempts = 0

print("I'm thinking of a number between 1 and 20.")

while True:
    guess = int(input("Your guess: "))
    attempts += 1

    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"Got it in {attempts} attempts!")
        break

import random loads Python’s built-in random-number tools, and random.randint(1, 20) picks a whole number from 1 to 20, including both ends. while True loops forever until the break on a correct guess.

Challenges: limit the player to five attempts, or ask “Play again?” at the end and start a new round if they type y.

Key points

  • Conditions are True/False questions built with ==, !=, >, <, >= and <=.
  • if / elif / else pick one path; indentation shows what’s inside each block.
  • for loops repeat over a sequence; range(a, b) stops before b.
  • while loops repeat until a condition becomes False, so make sure it eventually does.

Ready to organise your code into reusable pieces? Read Python Functions Made Simple.