This post is part of an ongoing series - see all the posts below.
So far, our scripts have run from top to bottom, one line after another, doing exactly what we told them to do. That works fine for simple tasks, but real automation is rarely that straightforward. You will often need your script to make decisions based on certain conditions, or repeat the same action for a list of devices, interfaces, or VLANs.
This is where control flow comes in. Control flow is a fancy term for the tools Python gives us to control the order in which our code runs. Instead of always going line by line, we can tell Python "if this is true, do that" or "repeat this for every device in my list." Once you get the hang of these, you will start to see how Python can save you hours of manual work.
In this chapter, we will cover if, elif, and else statements for making decisions, for and while loops for repeating actions, and a couple of useful keywords like break and continue that give you more control over how loops behave. By the end of the chapter, we will put it all together with a small networking example.
If Statements
The if statement is how you tell Python to do something only when a certain condition is true. It uses the comparison and logical operators we covered in the last chapter, and it always evaluates to either True or False.
The basic structure looks like this.
if condition:
# do something
The condition goes after the if keyword and is followed by a colon. The code that should run when the condition is true goes on the next line, indented with four spaces. Indentation is important in Python, it is how Python knows which lines belong to the if statement. Let's look at a simple example.
cpu_usage = 85
if cpu_usage > 80:
print("Warning: CPU usage is high")
Warning: CPU usage is high
Here, Python checks if cpu_usage is greater than 80. Since it is, the indented print statement runs. If cpu_usage had been 50, nothing would have been printed because the condition would be False.
else
Often, you want your script to do one thing if a condition is true and something else if it is false. That is what else is for.
cpu_usage = 45
if cpu_usage > 80:
print("Warning: CPU usage is high")
else:
print("CPU usage is normal")
CPU usage is normal
The else block runs only when the if condition is False. You do not write a condition after else, it just acts as a catch-all for everything that did not match the if.
elif
What if you have more than two possibilities? For example, you might want to check if CPU usage is high, medium, or low. That is where elif (short for "else if") comes in. You can have as many elif blocks as you need.
cpu_usage = 65
if cpu_usage > 80:
print("CPU usage is high")
elif cpu_usage > 50:
print("CPU usage is medium")
else:
print("CPU usage is low")
CPU usage is medium
Python checks each condition from top to bottom and runs the first one that matches. Once it finds a match, it skips the rest. So even though 65 is also greater than 0, the else block does not run because the elif already matched.
A Networking Example
Let's bring this back to networking. Imagine you ran a show interface command and stored the output in a variable. You want to print a different message depending on what is in the output.
interface_status = "up"
if interface_status == "up":
print("Interface is operational")
elif interface_status == "down":
print("Interface is down, check the cable")
else:
print(f"Unknown interface status: {interface_status}")
Interface is operational
Combining Conditions
You can use and, or, and not from the last chapter to build more complex conditions.
cpu_usage = 85
memory_usage = 90
if cpu_usage > 80 and memory_usage > 80:
print("Device is under heavy load")
Device is under heavy load
Both conditions need to be true for the message to print. If you used or instead, only one of them would need to be true.
For Loops
A for loop is how you tell Python to repeat the same action for every item in a collection. This is one of the most useful tools in Python because you almost always work with lists of things, devices, interfaces, VLANs, IP addresses, and you want to do the same thing to each one. The basic structure looks like this.
for item in collection:
# do something with item
The for keyword starts the loop, item is a variable name you pick (it can be anything), in is a keyword, and collection is whatever you want to loop through. Just like with if statements, the code that runs inside the loop is indented. Let's start with a simple example using a list of devices.
devices = ["r1_lnd_dc", "r2_lnd_dc", "r3_lnd_dc"]
for device in devices:
print(f"Connecting to {device}")
We have not covered lists in detail yet, that is coming in Chapter 5. For now, just know that a list is a collection of values written inside square brackets and separated by commas, devices above holds three device names. That is enough to follow along with loops.Connecting to r1_lnd_dc
Connecting to r2_lnd_dc
Connecting to r3_lnd_dc
Python goes through the list one item at a time, assigns the current item to the variable device, and runs the indented code. Once it reaches the end of the list, the loop stops.
devices = ["r1_lnd_dc", "r2_lnd_dc", "r3_lnd_dc"]
| | |
iteration 1 iteration 2 iteration 3
| | |
device = device = device =
"r1_lnd_dc" "r2_lnd_dc" "r3_lnd_dc"
| | |
v v v
Connecting to Connecting to Connecting to
r1_lnd_dc r2_lnd_dc r3_lnd_dc
Each time through the loop, device gets reassigned to the next item in the list, first "r1_lnd_dc", then "r2_lnd_dc", then "r3_lnd_dc". The loop stops once it runs out of items.
The variable name (device in this case) is something you choose. Python does not care what you call it, but pick a name that makes sense. If you are looping through a list of interfaces, call it interface. If you are looping through VLANs, call it vlan. Your future self will thank you.
You will notice I used the word "collection" here. A collection is just a general term for any data type that holds multiple items together. In Python, the proper term for something you can loop through is an iterable, anything you can iterate (go through) one item at a time. Lists, dictionaries, and strings are all iterables, and we will see a few more later in the series. For now, just think of an iterable as a container that holds a group of values, and a for loop is how you go through each one.
Looping Through Strings
A for loop is not just for lists. You can loop through any collection in Python, including strings. When you loop through a string, you get one character at a time.
hostname = "R1_LND"
for character in hostname:
print(character)
R
1
_
L
N
D
The range() Function
Sometimes you do not have a list to loop through, you just want to repeat something a certain number of times. Python has a built-in function called range() that helps with this.
for number in range(5):
print(number)
Output
0
1
2
3
4
range(5) generates numbers from 0 up to (but not including) 5. Remember, Python starts counting from 0.
range(5) --> 0 1 2 3 4
| | | | |
iter 1 iter 2 iter 3 iter 4 iter 5
| | | | |
number=0 number=1 number=2 number=3 number=4
| | | | |
v v v v v
0 1 2 3 4
Each time through the loop, number gets reassigned to the next value from range(5), starting at 0 and stopping right before 5. That is why you see 0 through 4 printed, five numbers in total, not six.
If you want it to start from a different number, you can pass two arguments.
for vlan_id in range(100, 105):
print(f"Creating VLAN {vlan_id}")
Creating VLAN 100
Creating VLAN 101
Creating VLAN 102
Creating VLAN 103
Creating VLAN 104
This is handy when you need to generate a range of VLANs, IP addresses, or interface numbers.
Looping Through a Dictionary
We have not covered dictionaries , that is coming in Chapter 5. For now, just know that a dictionary stores data as key-value pairs inside curly braces, each key works like a label, and the value is what that label points to.
In device below, "hostname" is a key and "r1_lnd_dc" is its value, same with "ip" and "vendor". Unlike a list, you do not access items by position, you access them by their key. That is enough to follow the loop examples below, we will cover everything else dictionaries can do later.
device = {
"hostname": "r1_lnd_dc",
"ip": "192.168.1.1",
"vendor": "cisco"
}
for key in device:
print(key)
hostname
ip
vendor
To get both the key and the value at the same time, use the .items() method.
device = {
"hostname": "r1_lnd_dc",
"ip": "192.168.1.1",
"vendor": "cisco"
}
for key, value in device.items():
print(f"{key}: {value}")
hostname: r1_lnd_dc
ip: 192.168.1.1
vendor: cisco
Notice that we used two variable names this time, key and value, separated by a comma. That is because .items() gives us two things on each loop, the key and its value. We will cover dictionaries in more detail later.
Combining for Loops with if Statements
This is where things get interesting. You can put an if statement inside a for loop to make decisions for each item.
interfaces = ["GigabitEthernet0/1", "GigabitEthernet0/2", "GigabitEthernet0/3"]
for interface in interfaces:
if "0/1" in interface:
print(f"{interface} is the uplink")
else:
print(f"{interface} is an access port")
GigabitEthernet0/1 is the uplink
GigabitEthernet0/2 is an access port
GigabitEthernet0/3 is an access port
The loop goes through each interface, and for each one, the if statement checks whether "0/1" is in the name.
Looping Through a List of Dictionaries
In real scripts, you will often have a list of dictionaries, one dictionary per device. You can loop through the list and access each dictionary like normal.
devices = [
{"hostname": "r1_lnd_dc", "ip": "192.168.1.1"},
{"hostname": "r2_lnd_dc", "ip": "192.168.1.2"},
{"hostname": "r3_lnd_dc", "ip": "192.168.1.3"}
]
for device in devices:
print(f"Connecting to {device['hostname']} at {device['ip']}")
Connecting to r1_lnd_dc at 192.168.1.1
Connecting to r2_lnd_dc at 192.168.1.2
Connecting to r3_lnd_dc at 192.168.1.3
You might be wondering about the device[’hostname’] syntax. This is how you access a value inside a dictionary using its key. You write the dictionary variable name, followed by square brackets, with the key name in quotes inside. So device[’hostname’] gives you the value stored under the hostname key, and device[’ip’] gives you the value under the ip key. We will cover this in more detail when we get to dictionaries properly, but for now, just remember that square brackets with a key inside is how you pull a specific value out of a dictionary.
While Loops
A while loop is similar to a for loop in that it repeats a block of code, but instead of going through each item in an iterable, it keeps running as long as a condition is True. Once the condition becomes False, the loop stops. The basic structure looks like this.
while condition:
# do something
Let's look at a simple example.
count = 0
while count < 5:
print(f"Count is {count}")
count = count + 1
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
- Python checks if
count < 5is true. It is, so the indented code runs. Inside the loop, we print the value and then increasecountby 1. - Python then checks the condition again. This keeps going until
countreaches 5, at which point the condition becomes false and the loop stops.
Notice that we had to manually update count inside the loop. This is the biggest difference between for and while loops. With a for loop, Python automatically moves to the next item for you. With a while loop, you are in charge of making sure the condition eventually becomes false. If you forget, you end up with an infinite loop, a loop that never stops. If that ever happens to you (and it will at some point), you can stop the script by pressing Ctrl + C in your terminal. Here is a quick example of an infinite loop.
while True:
print("Hello, World!")
The condition here is just True, which never changes. Python will keep printing Hello, World! forever until you stop it with Ctrl + C.

