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:
| Shape | What it does | Python tools |
|---|---|---|
| Sequence | Runs statements in order | Ordinary lines of code |
| Selection | Chooses which block to run | if, elif, else, match |
| Repetition | Runs a block more than once | for, 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.
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.
scores = [72, 88, 95]
total = 0
for score in scores:
total += score
print(total) # 255Use 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.
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:
breakleaves the loop immediately.continueskips the rest of the current pass and moves on to the next one.passdoes nothing. It is a placeholder for a block you have not written yet.
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.
for name in ["Ada", "Linus"]:
print("Hello,", name) # inside the loop: runs twice
print("Done") # outside the loop: runs onceIf 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 true | if |
| Pick one of several branches | if / elif / else |
| Do something for each item in a collection | for |
| Repeat a fixed number of times | for with range() |
| Repeat until something changes | while |
| Stop a loop early | break |
| Skip one item | continue |
| Compare one value against many patterns | match (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
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.
Frequently Asked Questions
What is control flow in Python?
What are the control flow statements in Python?
What is the difference between a for loop and a while loop?
Does Python have a switch statement?
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.
More in this topic
Nested Loops in Python
A nested loop is a loop inside another loop. See exactly what order the lines run in, how to work with grids and nested lists, and how to break out of both loops.
Python break, continue, and pass Explained
break exits a loop, continue skips to the next pass, and pass does nothing at all. See how each one works in for and while loops, and when to use them.
Python while Loops Explained
A while loop repeats a block for as long as a condition stays true. Learn the syntax, the while True pattern, how to validate input, and how to avoid infinite loops.