Python Control Flow Explained

Control flow is how a Python program decides which lines run, which are skipped, and which repeat. Meet if statements, for loops, while loops, and the keywords that steer them.

4 min read

Control flow is the order in which Python runs the lines of your program. By default that order is top to bottom, one line after another. Control flow statements change it: an if statement runs a block only when a condition is true, a for loop repeats a block once for each item in a collection, and a while loop repeats a block for as long as a condition stays true.

Almost every useful program needs these three tools. A login check is a decision. Adding up a shopping cart is a loop. Asking again until the user types a valid number is a loop with a decision inside it.

This article is the map for the control flow section. Each tool gets its own article with more examples.

The three shapes of a program

Every program, however large, is built from three shapes:

ShapeWhat it doesPython tools
SequenceRuns statements in orderOrdinary lines of code
SelectionChooses which block to runif, elif, else, match
RepetitionRuns a block more than oncefor, while

You already use sequence. The rest of this section teaches selection and repetition.

Decisions with if, elif, and else

An if statement tests a condition. When the condition is true, Python runs the indented block below it. When it is false, Python skips that block.

pythonpython
temperature = 31
 
if temperature > 30:
    print("It is hot today.")
elif temperature > 15:
    print("The weather is mild.")
else:
    print("It is cold.")

This prints It is hot today. Python checks the conditions from top to bottom and runs only the first block whose condition is true. The else block runs when none of them is.

The conditions are built from the comparison operators and logical operators you have already met. The full guide is writing conditional statements in Python.

Repeating with for loops

A for loop takes the items of a collection one at a time and runs its block once for each.

pythonpython
scores = [72, 88, 95]
total = 0
 
for score in scores:
    total += score
 
print(total)  # 255

Use a for loop when you know what you are looping over: the items of a list, the characters of a string, the keys of a dictionary, or a run of numbers from range(). See Python for loops explained for the details.

Repeating with while loops

A while loop repeats its block for as long as a condition stays true. Python checks the condition before every pass.

pythonpython
countdown = 3
 
while countdown > 0:
    print(countdown)
    countdown -= 1
 
print("Liftoff")

This prints 3, 2, 1, and then Liftoff. Use a while loop when you do not know in advance how many passes you need, for example when you keep asking for input until it is valid.

Something inside a while loop must eventually make its condition false. If countdown -= 1 were missing here, the loop would never end. Press Ctrl+C in the terminal to stop a program that is stuck in a loop.

Steering a loop: break, continue, and pass

Three small keywords adjust how a loop runs:

  • break leaves the loop immediately.
  • continue skips the rest of the current pass and moves on to the next one.
  • pass does nothing. It is a placeholder for a block you have not written yet.
pythonpython
for number in [4, 7, -1, 9]:
    if number < 0:
        break
    print(number)

This prints 4 and 7, then stops when it reaches the negative number. The 9 is never printed.

Indentation defines the blocks

Python uses indentation, not braces, to mark which lines belong to an if or a loop. Every line in a block must be indented by the same amount, and the standard is four spaces. A line that returns to the previous indentation level is outside the block.

pythonpython
for name in ["Ada", "Linus"]:
    print("Hello,", name)   # inside the loop: runs twice
print("Done")               # outside the loop: runs once

If you get an IndentationError, check that you have not mixed tabs and spaces. The article on Python syntax and indentation explains the rules.

Choosing the right tool

You want to...Use
Run code only when a condition is trueif
Pick one of several branchesif / elif / else
Do something for each item in a collectionfor
Repeat a fixed number of timesfor with range()
Repeat until something changeswhile
Stop a loop earlybreak
Skip one itemcontinue
Compare one value against many patternsmatch (Python 3.10 and later)

Once these tools feel natural, you are ready to package code into functions, which is the next section.

Rune AI

Rune AI

Key Insights

  • Control flow decides which lines run, which are skipped, and which repeat.
  • if, elif, and else choose between blocks; only the first true branch runs.
  • A for loop runs once per item in a collection or range.
  • A while loop runs for as long as its condition stays true.
  • break exits a loop, continue skips to the next pass, and pass does nothing.
  • Indentation, normally four spaces, defines which lines belong to a block.
RunePowered by Rune AI

Frequently Asked Questions

What is control flow in Python?

Control flow is the order in which Python runs the statements of a program. Without control flow statements, code runs from top to bottom once. With if, for, and while, a program can skip lines, choose between blocks, and repeat blocks.

What are the control flow statements in Python?

The main ones are if, elif, and else for decisions, for and while for repetition, and break, continue, and pass for steering loops. Python 3.10 added match for comparing a value against several patterns. try and except also change control flow when an error occurs.

What is the difference between a for loop and a while loop?

A for loop runs once for each item in a collection or range, so the number of passes is known up front. A while loop runs for as long as a condition stays true, so it suits cases where you cannot know the number of passes in advance.

Does Python have a switch statement?

Python has no switch keyword. Use an if, elif, else chain, or the match statement in Python 3.10 and later, which covers the same need and can also match the shape of data.

Conclusion

Control flow turns a list of instructions into a program that can decide and repeat. Start with if statements, add for loops for collections and while loops for open-ended repetition, and use break and continue only when they make a loop easier to read.