Skip to content
Home » Blog » Python for Network Engineers blog 18: Python if statements

Python for Network Engineers blog 18: Python if statements

Main blog image for Python for Network Engineers Blog 18 Python if statements showing a Python if statement code example and a network diagram with router, switch, host, and admin laptop

Python If Statements, Making Decisions That Actually Matter

Right, so you’ve got variables, data types, and operators working, haven’t you? Been through all the fundamentals in the first seventeen posts and mabye even the PCEP Supplement blogs. Now we’re getting to the good stuff – making your scripts actually think and make decisions based on what’s happening in your network using Python If Statements.

Python for Network Engineers Blog 17: Python Bitwise Operators

Here’s where most Python courses completely lose the plot again. They’ll have you checking if someone’s age is over 18, or working out if a number is even or odd, or deciding what to print based on someone’s favourite colour. I’m sitting there thinking, that’s lovely mate but I’ve got network devices to monitor, interface states to check, and VLAN configurations to validate. How’s working out if someone can vote going to help me automate my network then?

Thing is, I made this exact mistake when I started learning Python three years back. Found this online course that spent ages on theoretical examples. Checking if grades were A, B, or C. Working out if the weather was hot or cold. Complete waste of time for what I actually needed to do.

Few months later, had a proper network outage because one of our core switches was running too hot and I didn’t catch it in time. Thought there’s got to be a better way than manually checking temperatures every few hours. Found someone who explained conditional logic properly using networking examples. Made much more sense straight away. Instead of checking if the temperature outside was warm, I’m checking if the device temperature was above threshold.

So let’s do python if statements properly using network stuff that matters.

Right so if statements let you make decisions in your code based on whether something is true or false. You check a condition, and if it’s true, Python runs the code inside the if block. Simple as that. Like checking if device_status equals “up” and then printing “Device is operational” if it is.

device_status = "up"
if device_status == "up":
    print("Device is operational")

Or seeing if utilisation is greater than 80 and alerting about high usage.

utilisation = 85
if utilisation > 80:
    print("High utilisation detected")
vlan_id = 10
if vlan_id < 4095:
    print("Valid VLAN ID")

Much more relevant than checking if someone’s old enough to drive.

flow chart image displaying 4 vlans and using Python if statements for logical vlan flow

Now here’s something quite clever about if statements that I didn’t appreciate when I started. The condition after the if keyword must evaluate to either True or False. Python uses the comparison operators you’ve already learned to work this out. Greater than, less than, equals, not equals – they all return boolean values.

Actually had this come up last year. Was writing a script to check BGP session states and couldn’t work out why my if statement wasn’t working. Turned out I was using assignment (single equals) instead of comparison (double equals). Python was setting the variable instead of checking it. Felt like a right pillock once I spotted the mistake.

Look, networking’s absolutely stuffed with conditional decisions, isn’t it? Interface up or down. VLAN in range or out of range. Utilisation normal or excessive. Device temperature acceptable or too hot. Everything’s got some kind of threshold or state that needs checking.

Understanding python if statements properly means you can automate all these checks instead of doing them manually. Makes your monitoring scripts actually useful instead of just collecting data.

interface_state = "down"
if interface_state == "down":
    print("ALERT: Interface is down")

Much better than learning whether someone likes pizza.

The syntax catches people out constantly. Simple rule I use – start with the if keyword, then your condition, then a colon, then indent the code you want to run if the condition is true. Miss the colon and Python throws a syntax error. Get the indentation wrong and your code runs when it shouldn’t or doesn’t run when it should.

# Right way - proper indentation and colon
temperature = 65
if temperature > 60:
    print("Device running hot")
    print("Check cooling system")

# Wrong way - missing colon
# if temperature > 60
#     print("This won't work")

# Wrong way - no indentation  
# if temperature > 60:
# print("This won't work either")
Screenshot showing correct vs incorrect python if statements syntax with clear highlighting of the colon and indentation requirements. shows Python error messages for the incorrect examples

Got caught out by the indentation early on actually. Had a script that was supposed to alert when CPU usage was high, couldn’t work out why some lines were running when they shouldn’t. Spent ages debugging before I realised the indentation was wrong. Some lines were inside the if block, others weren’t. Python’s very fussy about getting the spacing exactly right.

Most common thing you’ll do with if statements in networking is checking interface status.

# Single interface check
interface_status = "up"
if interface_status == "up":
    print("Interface operational")

# Port speed validation
port_speed = 1000
if port_speed == 1000:
    print("Gigabit interface confirmed")

# Link utilisation monitoring  
current_utilisation = 75
if current_utilisation > 70:
    print("WARNING: High utilisation detected")

Always need to check if VLANs are in valid ranges too.

vlan_id = 99
if vlan_id > 0:
    print("VLAN ID is positive")

if vlan_id < 4095:
    print("VLAN ID within standard range")

management_vlan = 100
if management_vlan == 100:
    print("Management VLAN detected")

Critical for preventing hardware failures is checking device temperature.

device_temp = 68
if device_temp > 65:
    print("CRITICAL: Device overheating")

cpu_temp = 45
if cpu_temp < 50:
    print("CPU temperature normal")

Let me tell you about mistakes I see when people start working with configuration data. Made most of these myself at some point. Getting the string comparison right matters.

# Right way - exact match
bgp_state = "Established"
if bgp_state == "Established":
    print("BGP session active")

# Wrong way - case sensitivity issues
ospf_state = "full"
if ospf_state == "FULL":  # This won't match
    print("This won't print")

# Right way - handling case issues
if ospf_state.upper() == "FULL":
    print("OSPF adjacency up")

Case sensitivity bit me badly once. Had a monitoring script that was supposed to alert when BGP sessions went down. The router was sending “established” in lowercase, but I was checking for “Established” with a capital E. Missed three session failures before I worked out what was going on. Network team weren’t happy.

Terminal-style screenshot comparing correct and incorrect Python if statements syntax with networking examples, showing accurate quotes, colons, and indentation with real Python error messages

You’ll be checking what type of device you’re working with constantly.

device_type = "switch"
if device_type == "switch":
    print("Layer 2 device detected")

vendor = "Cisco"
if vendor == "Cisco":
    print("Using Cisco commands")

# Multiple condition checks
hostname = "SW1-ACCESS"
if hostname.startswith("SW"):
    print("Switch device identified")

Making sure configs are what you expect too.

spanning_tree_mode = "rapid-pvst"
if spanning_tree_mode == "rapid-pvst":
    print("Rapid PVST+ configured")

duplex_setting = "full"
if duplex_setting == "full":
    print("Full duplex configured")

This is where if statements become really useful for network engineers. Checking if values are within acceptable ranges. Critical for capacity planning is bandwidth utilisation.

interface_util = 82
if interface_util > 80:
    print("Interface approaching capacity")

backbone_util = 45
if backbone_util < 70:
    print("Backbone utilisation normal")

# Port counting
active_ports = 18
if active_ports > 20:
    print("Switch approaching port limit")

Keeping track of network performance means checking if latency_ms is greater than 10 for high latency alerts.

latency_ms = 15
if latency_ms > 10:
    print("High latency detected")

packet_loss = 2
if packet_loss > 1:
    print("Packet loss above threshold")

jitter = 8
if jitter < 5:
    print("Jitter within acceptable range")

Making sure devices aren’t running out of resources – if cpu_usage is greater than 75 then you know CPU usage is high.

cpu_usage = 78
if cpu_usage > 75:
    print("CPU usage high")

memory_usage = 45
if memory_usage < 80:
    print("Memory usage acceptable")

# Routing table size
route_count = 850000
if route_count > 800000:
    print("Large routing table detected")

Something that trips up loads of people when they start is boolean variables.

# Interface administrative state
interface_enabled = True
if interface_enabled:
    print("Interface administratively up")

# PoE status check
poe_enabled = False  
if poe_enabled:
    print("PoE is enabled")  # This won't print

# DHCP snooping status
dhcp_snooping = True
if dhcp_snooping:
    print("DHCP snooping active")

# Port security
port_security = False
if not port_security:
    print("Port security disabled")

Had this confusion early on. Kept writing if interface_enabled equals True which works but looks amateurish. The boolean variable itself is already True or False, so you can just check it directly. Much cleaner code.

Thing is, once you get if statements sorted, loads of networking tasks become much easier. Checking multiple interface conditions like if status equals “up” and speed equals 1000.

hostname = "SW1-ACCESS"
interface = "GigabitEthernet0/1"
status = "up"
speed = 1000

if status == "up":
    print(f"Interface {interface} on {hostname} is operational")

if speed == 1000:
    print("Gigabit speed confirmed")

if hostname.startswith("SW"):
    print("Switch management required")

Making sure VLAN settings are correct – if vlan_state equals “active” then you know the VLAN is working.

vlan_id = 10
vlan_name = "USERS"
vlan_state = "active"

if vlan_id >= 1:
    print("VLAN ID valid")

if vlan_state == "active":
    print(f"VLAN {vlan_id} ({vlan_name}) is active")

if vlan_name == "USERS":
    print("User VLAN detected")

Checking critical device parameters like CPU, temperature, and uptime.

device_name = "R1-EDGE-RTR"
cpu_percent = 45
temperature = 58
uptime_days = 127

if cpu_percent < 70:
    print(f"{device_name} CPU usage normal")

if temperature < 60:
    print(f"{device_name} temperature acceptable")

if uptime_days > 30:
    print(f"{device_name} has been stable for {uptime_days} days")

Let me tell you about the mistakes I see constantly when people start using if statements for network automation. Classic beginner error is using assignment instead of comparison. Writing if vlan_id equals 10 using single equals assigns 10 to vlan_id instead of checking if it equals 10. That’s a syntax error right there.

vlan_id = 20

# Wrong - this assigns 10 to vlan_id
if vlan_id = 10:
    print("This is a syntax error")

# Right - this checks if vlan_id equals 10  
if vlan_id == 10:
    print("This compares values correctly")

Python is fussy about syntax too. Miss the colon after your if condition and you get an error.

interface_speed = 100

# Wrong - missing colon
if interface_speed > 10
    print("Syntax error")

# Right - colon required
if interface_speed > 10:
    print("Fast interface detected")

Wrong indentation catches everyone out initially. No indentation means the print statement isn’t inside the if block.

device_status = "up"

# Wrong - no indentation
if device_status == "up":
print("This won't work")

# Right - proper indentation
if device_status == "up":
    print("Device operational")
    print("Monitoring continues")

Took me ages to get comfortable with Python’s indentation requirements. Coming from other languages where brackets define code blocks, having to get the spacing exactly right felt weird.

Let me show you actual scenarios where if statements make network management much easier. BGP session monitoring – checking if routing protocols are working properly.

bgp_neighbor = "10.1.1.2"
session_state = "Established"
received_routes = 145000

if session_state == "Established":
    print(f"BGP session to {bgp_neighbor} is up")

if received_routes > 100000:
    print("Full routing table received")

if received_routes < 50000:
    print("WARNING: Incomplete routing table")

Switch port management for monitoring access layer connectivity.

switch_name = "SW2-ACCESS"
port = "FastEthernet0/12"
port_status = "up"
vlan_assignment = 20

if port_status == "up":
    print(f"Port {port} on {switch_name} is active")

if vlan_assignment == 20:
    print("Port assigned to VOICE VLAN")

if switch_name.endswith("ACCESS"):
    print("Access layer switch detected")

Bandwidth capacity planning makes sure links aren’t overloaded.

link_name = "WAN-PRIMARY"
current_utilisation = 78
link_capacity = 1000  # Mbps
threshold = 80

if current_utilisation > threshold:
    print(f"WARNING: {link_name} utilisation at {current_utilisation}%")

if current_utilisation < 50:
    print(f"{link_name} utilisation normal at {current_utilisation}%")

if link_capacity == 1000:
    print("Gigabit WAN link confirmed")
Network monitoring dashboard showing real-time utilisation graphs with threshold lines and alert indicators using data from basic python if statements
Dashboard generated using above python if statements data

The PCEP exam covers basic if statement syntax that you need to understand properly. Basic conditional structure tests understanding of fundamental syntax.

# Basic if statement format
condition = True
if condition:
    print("Condition was true")

# Numeric comparison
value = 25
if value > 20:
    print("Value exceeds threshold")

# String comparison  
status = "active"
if status == "active":
    print("Status is active")

Boolean evaluation covers how conditions become True or False.

# Direct boolean check
network_up = True
if network_up:
    print("Network is operational")

# Comparison operators
port_count = 24
if port_count >= 24:
    print("Full port density")

# String method results
hostname = "RT1-CORE"
if hostname.startswith("RT"):
    print("Router identified")

Code block structure is about getting the indentation and syntax exactly right.

temperature = 72
if temperature > 70:
    print("Temperature alert")
    print("Check cooling system")
    print("Monitor closely")
# Code here is outside the if block
print("This always runs")

The exam will test your understanding of when code runs and when it doesn’t based on indentation levels.

Understanding python if statements properly is fundamental to everything else you’ll do with network automation. Decision-making logic is the foundation of useful scripts. Get if statements wrong and you’ll spend ages debugging scripts that don’t behave the way you expect. Get them right and automation starts making your job much easier.

The key thing is using if statements for actual network conditions. Interface states, device health, configuration validation, performance thresholds. Not checking abstract conditions that have nothing to do with your daily work. When you’re monitoring network infrastructure, capacity planning, or validating configurations, conditional logic becomes essential.

That’s basic if statements sorted properly. You understand the syntax, how to check network conditions, common mistakes to avoid, and practical applications for real network engineering tasks. Much more useful than learning about theoretical decision trees that don’t help anyone manage actual network infrastructure.


External Link: Python Conditional Statements Documentation – official Python documentation for control flow statements

Leave a Reply

Your email address will not be published. Required fields are marked *