From point A to point B
Point A: you already know how to store data in variables, lists and dictionaries, but your programs run top to bottom, the same way every time. Point B: by the end of this chapter, your code will make decisions based on the data and repeat tasks for every router, interface or log line you have.
Every example is a complete script: copy it with the Copy button, save it as a .py file and run it.
Conditionals with if and indentation
A program that only runs commands in a row isn't much use. Conditionals let you ask a question and act on the answer. This is where the booleans and comparison operators you saw with the basic types come in.
The minimal form is if, followed by a condition and a colon. On the next lines, indented, goes the block that runs only when the condition is true.
status = "up"
if status == "up":
print("The interface is active")
print("You can send traffic")
print("Check complete")
The interface is active
You can send traffic
Check complete
The first 2 calls to print are indented: they belong to the if. The last one isn't, so it always runs. If you move the second line to the left, the program means something else:
status = "down"
if status == "up":
print("The interface is active")
print("You can send traffic")
You can send traffic
Now the program promises traffic while the interface is down. That's the power of indentation in Python: it isn't decoration, it's syntax.
Languages like Java, C or JavaScript mark blocks with braces { }, and indentation is just a good habit. Python makes it mandatory. The result is code that reads the same way it runs.
String status = "up";
if (status.equals("up")) {
System.out.println("The interface is active");
System.out.println("You can send traffic");
}
If you forget the indentation, Python stops before running anything and tells you where:
File "indent.py", line 3
print("active")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 2
print as a statement (print "text"). In Python 3, print() is a function and takes parentheses. The PEP 8 style guide recommends 4 spaces per level, and Python 3 rejects with TabError any block that mixes tabs and spaces inconsistently. Set your editor to insert 4 spaces when you press Tab.Two paths: if and else
What if you want to do something when the condition is not met? You could write a second if with the opposite condition:
status = "up"
if status == "up":
print("The interface is active")
if status != "up":
print("Alert: the interface isn't responding")
It works, but it repeats the comparison and forces you to keep 2 conditions in sync. The else clause (“otherwise”) covers every other case in a single piece:
status = "down"
if status == "up":
print("The interface is active")
else:
print("Alert: the interface isn't responding")
print("Check complete")
Alert: the interface isn't responding
Check complete
Read it out loud: “if the status is up, report that it's active; otherwise, raise the alert.” Exactly one of the 2 blocks runs.
Many paths: elif
When there are more than 2 possibilities, chain conditions with elif, short for “else if.” Let's classify the latency of a link:
latency_ms = 85
if latency_ms < 0:
print("Invalid measurement")
elif latency_ms < 50:
print("Good latency")
elif latency_ms < 150:
print("Acceptable latency")
else:
print("High latency: check the link")
Acceptable latency
Python evaluates the conditions in order, top to bottom. As soon as one is true, it runs that block and jumps to the end of the whole structure. If none is met, it runs the else, which is optional.
Order matters. A value of 30 ms also meets latency_ms < 150; that's why the strictest condition goes first.
The ternary operator
Many languages have a ? : operator to pick a value in a single line. Python uses words: A if C else B. It evaluates condition C; if it's true, the result is A, and if not, B.
vlan = 120
kind = "even" if vlan % 2 == 0 else "odd"
print(f"VLAN {vlan} is {kind}")
lost_packets = 3
status = "lossy" if lost_packets > 0 else "clean"
print(status)
VLAN 120 is even
lossy
It's an expression: it produces a value you can assign or pass to a function. Use it for short choices. If the logic grows, go back to the multi-line if, which reads better.
New: match and case
The original book explains that Python has no switch and suggests a dictionary instead. That trick is still useful when all you need is to translate one value into another:
ports = {22: "ssh", 80: "http", 443: "https", 161: "snmp"}
for port in (443, 161, 8080):
service = ports.get(port, "unknown")
print(port, service)
443 https
161 snmp
8080 unknown
Since Python 3.10 there's also the match statement, called structural pattern matching (PEP 634). It compares a value against several case patterns and runs the first one that fits. The _ pattern acts as a wildcard, and | joins alternatives.
def describe(severity):
match severity:
case 0 | 1 | 2:
return "emergency, alert or critical"
case 3:
return "error"
case 4:
return "warning"
case 5 | 6:
return "notice or informational"
case 7:
return "debug"
case _:
return "invalid level"
for level in (1, 3, 6, 9):
print(level, "→", describe(level))
1 → emergency, alert or critical
3 → error
6 → notice or informational
9 → invalid level
You haven't seen def yet: it's coming in the next chapter. For now, just know that it groups the match under a name. Levels 0 to 7 are the syslog severities.
The strength of match lies in structured data. It can recognize the shape of a dictionary and capture values into variables, which is very handy with JSON responses from an API:
response = {"name": "Gi0/1", "status": "down", "vlan": 20}
match response:
case {"status": "up", "name": name}:
print(f"{name} is active")
case {"status": "down", "name": name}:
print(f"{name} is down: open a ticket")
case _:
print("Unexpected API response")
Gi0/1 is down: open a ticket
Unlike the switch in C, you don't need a break: only one case runs. For now, hold on to the idea; match has many more patterns you'll pick up with practice.
Loops with while
Conditionals choose what runs. Loops decide how many times. The while loop repeats its block as long as the condition is true.
attempt = 0
while attempt < 3:
attempt = attempt + 1
print(f"Connection attempt {attempt} to the router")
print("No more attempts")
Connection attempt 1 to the router
Connection attempt 2 to the router
Connection attempt 3 to the router
No more attempts
Follow the execution step by step. attempt starts at 0 and 0 < 3, so it enters the loop, adds 1 and prints. It evaluates again: 1 < 3, another round. When attempt reaches 3, the condition is false and the program continues after the loop.
What happens if you forget the line attempt = attempt + 1? The variable stays at 0 forever and the loop never ends. That's an infinite loop. If it happens to you, stop the program with Ctrl+C in the terminal.
"text " + str(number), because Python doesn't add strings and numbers. That rule still holds. Today the usual approach is f-strings, like f"Attempt {attempt}", which convert the value for you.Exit and skip: break and continue
Sometimes an infinite loop is exactly what you want. Think of a console that repeats commands until you type exit. The break keyword leaves the loop on the spot.
while True:
command = input("router> ")
if command == "exit":
break
print(f"Running: {command}")
print("Session closed")
If you type show version and then exit, you'll see this:
router> show version
Running: show version
router> exit
Session closed
The input() function shows the text you pass it and waits for the person to type something and press Enter. It returns what they typed as a string.
You can write the same program without break, using a flag variable that controls the loop. Both ways are valid; pick whichever reads better in each case.
done = False
while not done:
command = input("router> ")
if command == "exit":
done = True
else:
print(f"Running: {command}")
The other keyword is continue. It doesn't leave the loop: it abandons the current round and goes straight to the next one. Here we only configure the odd VLANs:
vlan = 0
while vlan < 10:
vlan = vlan + 1
if vlan % 2 == 0:
continue
print(f"Configuring VLAN {vlan}")
Configuring VLAN 1
Configuring VLAN 3
Configuring VLAN 5
Configuring VLAN 7
Configuring VLAN 9
raw_input() to read from the keyboard. In Python 3 that function is called input() and always returns a string. The old Python 2 input(), which evaluated what you typed as code, no longer exists.Walk through collections with for and range
Python's for loop doesn't count positions: it walks through the elements of a collection, one by one. Read the header as a sentence: “for each interface in interfaces.”
interfaces = ["Gi0/0", "Gi0/1", "Gi0/2"]
for interface in interfaces:
print(f"interface {interface}")
print(" no shutdown")
interface Gi0/0
no shutdown
interface Gi0/1
no shutdown
interface Gi0/2
no shutdown
On each round, Python takes the next element from the list and stores it in the variable interface. On the first it's "Gi0/0", on the second "Gi0/1" and on the third "Gi0/2". You just generated configuration for 3 interfaces with 4 lines of code.
In C or classic Java you walk through an array with an index i that goes from 0 to the size minus 1. Python avoids that counter because you almost never need it. If you really want the position, use enumerate():
routers = ["core-01", "dist-01", "acc-01"]
for position, name in enumerate(routers, start=1):
print(position, name)
1 core-01
2 dist-01
3 acc-01
And if you want to count, like in C? The range() function generates a sequence of integers. With 2 arguments it goes from the first up to the second, without including it. A third argument sets the step.
for vlan in range(30, 35):
print(f"vlan {vlan}")
print(list(range(5)))
print(list(range(10, 51, 10)))
print(range(30, 51))
vlan 30
vlan 31
vlan 32
vlan 33
vlan 34
[0, 1, 2, 3, 4]
[10, 20, 30, 40, 50]
range(30, 51)
Look at the last line: range doesn't create a list. It's a lazy object that produces each number when the loop asks for it, so range(1_000_000) doesn't take up memory for a million integers. If you need the list, convert it with list().
break and continue work the same way inside for. This loop reviews a syslog log, ignores configuration changes and stops at the first outage:
logs = [
"%LINK-3-UPDOWN: Interface Gi0/1, changed state to up",
"%SYS-5-CONFIG_I: Configured from console",
"%LINK-3-UPDOWN: Interface Gi0/2, changed state to down",
"%SYS-5-RESTART: System restarted",
]
for line in logs:
if "SYS-5-CONFIG" in line:
continue
if "down" in line:
print("First outage found:", line)
break
print("Reviewed:", line)
Reviewed: %LINK-3-UPDOWN: Interface Gi0/1, changed state to up
First outage found: %LINK-3-UPDOWN: Interface Gi0/2, changed state to down
range() returned a full list, and xrange() existed for the lazy version. Python 3 removed xrange() and turned range() into the lazy object. Underscores in numeric literals, like 1_000_000, have existed since Python 3.6.Challenge
Answer before you open the solution.
1. In an if, how does Python know which lines belong to the block?
By the indentation. All the lines at the same indentation level under the colon form the block. The first line that moves back to the left is already outside. Use 4 spaces per level.
2. What does print("high" if 200 > 150 else "normal") print?
high. The condition 200 > 150 is true, so the ternary operator returns the value to the left of the if.
3. What's the difference between break and continue?
break leaves the loop; continue jumps to the next round. With break, the program carries on after the loop. With continue, it skips the rest of the block for that round and goes back to the header.
4. Which numbers does range(10, 40, 10) produce?
10, 20 and 30. The upper limit, 40, is never included. The third argument says it moves in steps of 10.
5. In a match, what does the case _: pattern do?
It catches any value. It's the wildcard: it runs if no earlier case matched. It plays the role of else or the default in other languages.
Key takeaways
- In Python, indentation defines the blocks; use 4 spaces per level.
if,elifandelsechoose a single path, evaluated in order from top to bottom.A if C else Bpicks a value in a single expression.match(Python 3.10+) compares a value or a structure against several patterns.whilerepeats as long as a condition holds; make sure something eventually makes it false.forwalks through the elements of a collection;range()andenumerate()handle counting and positions.breakleaves the loop andcontinuemoves on to the next round.
In the next chapter, you'll package this code into reusable functions, with parameters and return values.
Official resources
- Tutorial: more control flow toolsdocs.python.org
- Reference: compound statements (if, while, for, match)docs.python.org
- What's new in Python 3.10: structural pattern matchingdocs.python.org
- PEP 636: structural pattern matching tutorialpeps.python.org
- PEP 8: style guide for Python codepeps.python.org
Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.