Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. control-flow
11 min read

Control Flow

A program that runs every line once, top to bottom, cannot do much. Control flow is how Python decides which lines run and how many times: branching on a condition, looping over data, and stopping early when the answer is found. Python's versions of these are short, and they lean on the indentation rules from Basic Syntax instead of braces.

Truthiness

Every condition in Python is evaluated for its truthiness. A condition doesn't have to be a bool: any object can be tested, and Python decides whether it counts as true or false.

These values are falsy, meaning they count as false:

  • False and None
  • Zero of any numeric type: 0, 0.0
  • Empty containers: "", [], (), {}, set(), b""

Everything else is truthy. The bool() function shows how Python sees a value:

python
1bool(0)          # Return: False
2bool(-1)         # Return: True
3bool("")         

This makes the idiomatic way to check for an empty container short:

python
1if lines:
2    print("got input")
Warning
Truthiness can't tell 0, "" and None apart, since all three are falsy. When 0 is a valid value, such as a port number or an index, test for None explicitly with if x is None: instead of if not x:.

Conditionals

if, elif, else

An if statement runs its block only when its condition is truthy. elif (short for "else if") adds more conditions, checked in order, and else runs when none of them matched. Only the first matching branch runs:

python
1score = 72
2
3if score >= 90:
4    grade = "A"
5elif

Python has no switch statement in the C sense; a chain of elif is the usual replacement, along with the match statement below.

Comparisons

The comparison operators are ==, !=, <, <=, > and >=. Unlike most languages, Python lets you chain them, which reads like math:

python
1x = 5
20 < x < 10           # Return: True, same as 0 < x and x < 10
31 <= x <= 3          # Return: False

Two more operators test membership and identity:

  • in and not in check whether a value is inside a container: "flag" in line, port not in (80, 443). For strings, in searches for a substring.
  • is and is not check whether two names refer to the same object. Use them for None (x is None), and == for everything else.

and, or, not

Conditions are combined with the keywords and, or and not; Python doesn't use &&, || or ! for these. Both and and or short-circuit: they stop evaluating as soon as the answer is known. That makes it safe to guard a check that would otherwise fail:

python
1lst = []
2if lst and lst[0] == "admin":    # lst[0] is never evaluated when lst is empty
3    print(

and and or also return one of their operands, not necessarily a bool. or returns the first truthy value, which is a common way to supply a default:

python
name = "" or "anonymous"     # name = "anonymous"

Conditional Expressions

For a simple choice between two values, the conditional expression fits on one line. It reads as "this if the condition holds, else that":

python
1n = 7
2parity = "odd" if n % 2 else "even"    # parity = "odd"

for Loops

A for loop runs its block once for every item in an iterable: anything that can produce its items one at a time, such as a list, a string, a dictionary, a file or a range. The loop variable takes each item in turn:

python
1for port in [22, 80, 443]:
2    print("scanning", port)
scanning 22
scanning 80
scanning 443

Looping over a string gives its characters, and looping over a dictionary gives its keys:

python
1for ch in "abc":
2    print(ch)          # a, then b, then c
3
4user = {"name":

range

To loop a set number of times, use range. range(stop) counts from 0 up to, but not including, stop. range(start, stop) picks the starting point, and range(start, stop, step) sets the increment, which can be negative:

python
1list(range(5))            # Return: [0, 1, 2, 3, 4]
2list(range(2, 6))         # Return: [2, 3, 4, 5]

The stop value is excluded for the same reason slicing excludes it: range(len(lst)) produces exactly the valid indexes of lst.

enumerate and zip

If you're coming from C, the natural way to loop over a list is by index:

python
1names = ["alice", "bob", "carol"]
2for i in range(len(names)):
3

This works, but it's rarely the right shape in Python. Loop over the items directly, and when you also need the index, use enumerate, which produces (index, item) pairs:

python
1for i, name in enumerate(names):
2    print(i, name)            # 0 alice, 1 bob, 2 carol

enumerate(names, 1) starts counting at 1 instead, which is handy for line numbers.

To walk two sequences side by side, use zip, which pairs up their items and stops at the end of the shorter one:

python
1names = ["alice", "bob", "carol"]
2uids = [1000, 1001, 1002]
3
Don't change a list while looping over it
Adding or removing items from a list inside a for loop over that same list makes the loop skip or repeat items. Loop over a copy (for x in lst[:]:) or build a new list instead.

while Loops

A while loop repeats its block as long as its condition stays truthy. Use it when you don't know in advance how many times to loop, such as repeating until a value converges or until input runs out:

python
1n = 27
2steps = 0
3while n != 1:
4    n = n // 2

If the condition never becomes false, the loop runs forever. Press Ctrl+C to interrupt a script that's stuck.

while True: loops on purpose, with a break inside deciding when to stop. It's the usual shape for reading input until a sentinel value:

python
1while True:
2    line = input("> ")
3    if line == "quit":
4        break

break, continue, and else

Two statements change the flow inside any loop:

  • break leaves the loop immediately.
  • continue skips the rest of the current pass and moves on to the next item.
python
1for n in range(10):
2    if n % 2 == 0:
3        continue          

Loops in Python can also have an else clause, which runs only if the loop finished without hitting a break. It replaces the "found" flag you would otherwise need when searching:

python
1for n in [4, 6, 9, 10]:
2    if n % 2 == 1:

The else here belongs to the for, not to the if. It's an unusual feature, and plenty of Python programmers avoid it, but you'll see it in other people's code.

The pass statement does nothing at all. Python needs at least one statement in every block, so pass stands in where you have nothing to write yet:

python
1for line in lines:
2    pass    # TODO: parse each line

match Statements

Python 3.10 added the match statement, which compares a value against a series of patterns and runs the first one that fits. In its simplest form it works like C's switch, but without fall-through between cases:

python
1command = "up"
2
3match command:
4    case "up":
5        y = -

The _ pattern matches anything, so it acts as the default case. Several values can share a case with |, as in case "up" | "north":.

Patterns can do more than compare values. They can unpack a sequence and bind its parts to names, which makes match a clean way to handle parsed input with different shapes. Here, each line of input is split into words and matched on its structure:

python
1def run(line):
2    match line.split():
3        case [

case ["forward", n] only matches a list of exactly two items whose first item is "forward", and it binds the second item to n. A case can also carry a guard, an if that must be true as well:

python
1match point:
2    case (0, 0):
3        print("origin")
4
Tip
match needs Python 3.10 or newer. On older versions it's a SyntaxError, so stick to if/elif in scripts that have to run on old systems.
# Return: False
4bool("False") # Return: True, it's a non-empty string
5bool([]) # Return: False
6bool([0]) # Return: True, the list has one item
score
>=
80
:
6 grade = "B"
7elif score >= 70:
8 grade = "C"
9else:
10 grade = "F"
11
12print(grade) # Console: C
"first user is admin"
)
"echo"
,
"uid"
:
1000
}
5for key, value in user.items():
6 print(key, value) # name echo, then uid 1000
3list(range(0, 10, 3)) # Return: [0, 3, 6, 9]
4list(range(5, 0, -1)) # Return: [5, 4, 3, 2, 1]
print
(
i
,
names
[
i
]
)
for
name
,
uid
in
zip
(
names
,
uids
)
:
4 print(name, uid) # alice 1000, bob 1001, carol 1002
if
n
%
2
==
0
else
3
*
n
+
1
5 steps += 1
6
7print(steps) # Console: 111
5 print("you said", line)
# skip even numbers
4 if n > 7:
5 break # stop entirely once past 7
6 print(n) # 1, 3, 5, 7
3 print("first odd number:", n)
4 break
5else:
6 print("no odd numbers")
1
6 case "down":
7 y = 1
8 case _:
9 y = 0
"forward"
,
n
]
:
4 return ("x", int(n))
5 case ["up", n]:
6 return ("y", -int(n))
7 case ["down", n]:
8 return ("y", int(n))
9 case ["reset"]:
10 return ("reset", 0)
11 case _:
12 raise ValueError(f"bad command: {line}")
13
14run("forward 5") # Return: ('x', 5)
15run("reset") # Return: ('reset', 0)
case
(
x
,
0
)
:
5 print("on the x-axis at", x)
6 case (x, y) if x == y:
7 print("on the diagonal")
8 case (x, y):
9 print("somewhere else")