Skip to content
Home » Blog » Python for Network Engineers Blog 5: Python Comments

Python for Network Engineers Blog 5: Python Comments

main blog post image for the python comments post

Python Comments – Why They’re Not Just Useless Text

Right, so you’ve written your first Python script and you’ve spotted this # symbol in your code. You’re probably thinking “It’s just Python comments, how important can they be?”

Python for Network Engineers Blog 4: Python Print Function

Well, let me tell you something about python comments that most people get completely wrong. They’re not just little notes you add when you can be bothered. Understanding comments properly is actually fundamental to programming, and it’s part of the PCEP requirements too.

Most tutorials treat comments like an afterthought. Write the code, then maybe add a comment if you remember. That’s backwards. Comments should be part of how you think through problems, not something you stick on at the end.

What Comments Actually Do

Alright, let’s start with the basics. Python comments are text that Python completely ignores when it runs your code. When Python sees a # symbol, it ignores everything from that point to the end of the line.

print("This runs")  # This gets ignored
# This whole line gets ignored
print("This also runs")

Simple enough. But here’s the thing – just because Python ignores comments doesn’t mean they’re not important. Comments are how you talk to future you and anyone else who needs to understand your code.

Think about it. You wouldn’t configure a router without documenting what each interface does, would you? Same principle with code.

How the Hash Symbol Works

The # tells Python “ignore everything from here to the end of the line”. Doesn’t matter what comes after – could be English text, could be more Python code, could be complete rubbish. It all gets ignored.

hostname = "SW1-ACCESS"  # This is a comment
vlan_id = 10            # So is this
# print("This won't run because it's commented out")

You can stick the # anywhere on a line, and everything after it becomes a comment. Pretty flexible.

Why Comments Actually Matter

Now, you might be wondering why PCEP bothers testing comments if they’re just ignored text. Here’s the thing – understanding comments shows you understand how programming actually works.

You’ll Read Code Way More Than You Write It

You write a piece of code once. But you’ll read it dozens of times. When you’re debugging, when you’re updating it, when you come back to it six months later and can’t remember what the hell you were thinking.

Without comments, you’ll spend ages trying to figure out what your own code does. With good comments, you understand it immediately.

# Without comments - what's this doing?
device_list = ["SW1-ACCESS", "SW2-ACCESS", "R1-EDGE-RTR"]
for device in device_list:
    if "SW" in device:
        port_count = 24
    else:
        port_count = 4
    print(device, port_count)

You have to read through that and work out what it’s doing.

# With comments - obvious immediately
# List of devices in the main building
device_list = ["SW1-ACCESS", "SW2-ACCESS", "R1-EDGE-RTR"]

# Work out port count based on device type
for device in device_list:
    if "SW" in device:  # Switches have 24 ports
        port_count = 24
    else:              # Routers have 4 ports
        port_count = 4
    print(device, port_count)

Now it’s crystal clear what’s happening and why.

Comments Show Your Thinking

Good python comments don’t just explain what the code does – they explain why you did it that way. This is crucial when you’re learning because it forces you to think about your approach.

# Calculate percentage but avoid decimals in output
# Using int() to round down to whole numbers
utilization = int((used_ports / total_ports) * 100)

The comment explains not just what’s happening, but why you chose that particular method.

Before/after code comparison showing the same functionality with and without helpful python comments

Different Ways to Use Comments

There’s a few different ways you can use python comments, and knowing when to use each makes your code much more professional.

Basic Line Comments

Everything after # gets ignored:

# This is a complete comment line
print("Checking device status")  # This is an end-of-line comment

Multiple Line Comments

When you need to explain something complex, use several comment lines:

# This script checks device status across the network
# It connects to each device and runs basic health checks
# Results get saved to a log file for later review
# 
# You need Python 3.8 or newer to run this
# Make sure you can reach all devices before starting

Commenting Out Code

You can disable code temporarily without deleting it:

hostname = "SW1-ACCESS"
print(hostname)
# print("Debug information")  # Disabled for now

This is brilliant when you’re testing things and want to quickly enable or disable certain bits.

Common Mistakes People Make

Let me tell you about the mistakes I see when people are learning python comments.

Writing No Comments At All

# Bad - no explanation
devices = ["SW1-ACCESS", "SW2-ACCESS", "R1-EDGE-RTR"]
for device in devices:
    if "SW" in device:
        print(device, "24 ports")
    else:
        print(device, "4 ports")

You have to puzzle out what this does by reading the code carefully.

Stating the Completely Obvious

# Bad - pointless comments
x = 10        # Set x to 10
y = 20        # Set y to 20  
z = x + y     # Add x and y
print(z)      # Print z

These comments waste time and add nothing useful.

Writing Essays Instead of Code Comments

# Bad - comment is longer than the code
# This creates a variable called hostname and assigns it the value
# SW1-ACCESS which represents our primary access switch that's
# located in Building A and handles all the user connections
hostname = "SW1-ACCESS"

Keep comments focused and concise.

Letting Comments Get Out of Date

# Wrong - comment doesn't match the code
total_ports = 48  # Device has 24 ports

Out-of-date comments are worse than no comments because they mislead you.

How to Write Good Comments

Right, so here’s what I’ve learned about writing decent comments after years of reading terrible code.

Plan with Comments First

Don’t write code then add comments. Write comments first to plan what you’re doing, then write code to match.

# Work out if this is a switch or router
# Switches start with SW, routers start with R

# Check the first two characters of hostname
if hostname.startswith("SW"):
    device_type = "Switch"
elif hostname.startswith("R"):
    device_type = "Router"
else:
    device_type = "Unknown"

Writing the comments first helps you think through the logic.

Explain Why, Not What

Bad comments explain what the code does. Good comments explain why you’re doing it.

# Bad - explains what
vlan_id = 10  # Set VLAN to 10

# Good - explains why  
vlan_id = 10  # Sales team uses VLAN 10 per company policy

Keep Comments Up to Date

If you change the code, update the comments. Nothing worse than comments that don’t match what the code actually does.

Don’t Comment Everything

Not every line needs a comment. If the code is clear, don’t add pointless comments.

# Bad - unnecessary comments
hostname = "SW1-ACCESS"  # Set hostname
print(hostname)          # Print hostname

# Good - only comment where it adds value
hostname = "SW1-ACCESS"  # Main building access switch
print(hostname)

Using Comments for Network Stuff

Let’s look at how to use python comments effectively when you’re working with networking concepts.

Document Your Network Setup

# Lab network layout
# R1-EDGE-RTR (192.168.100.1) - connects to internet
# R2-CORE-RTR (192.168.100.2) - internal routing
# SW1-ACCESS (192.168.100.11) - Building A users
# SW2-ACCESS (192.168.100.12) - Building B users

devices = ["R1-EDGE-RTR", "R2-CORE-RTR", "SW1-ACCESS", "SW2-ACCESS"]

Explain VLAN Assignments

# VLAN setup per company standards
# VLAN 10 - Sales (subnet 10.1.10.0/24)
# VLAN 20 - Engineering (subnet 10.1.20.0/24)  
# VLAN 30 - Guests (subnet 10.1.30.0/24)
# VLAN 99 - Management (subnet 192.168.100.0/24)

sales_vlan = 10
engineering_vlan = 20
guest_vlan = 30
management_vlan = 99

Document Interface Conventions

# Interface naming rules:
# Gi0/1 = uplink to core
# Gi0/2-24 = user access ports
# Fa0/1 = management

uplink_interface = "GigabitEthernet0/1"
management_interface = "FastEthernet0/1"

Explain Protocol Choices

# Using OSPF for internal routing
# Single area for simplicity in this lab
# Could use EIGRP but OSPF works with more vendors

routing_protocol = "OSPF"
ospf_area = 0

Comments and the REPL vs Scripts

Comments work a bit differently depending on whether you’re using the Python REPL or writing script files.

In the REPL

You mainly use comments for quick notes:

>>> hostname = "SW1-ACCESS"  # Testing with lab switch
>>> print(hostname)
SW1-ACCESS
>>> # This device is in Building A
>>> location = "Building A"

Don’t usually write long comments in the REPL because it’s for quick experiments.

In Script Files

Scripts need more detailed commenting:

# device_info.py
# 
# Shows basic device information for lab equipment
# Used for learning Python fundamentals
#
# Needs Python 3.8 or newer

# Device details for our lab setup
hostname = "SW1-ACCESS"    # Main access switch
location = "Building A"    # Primary office building
device_type = "Switch"     # Layer 2 switch

# Show the information
print("Device Information")
print("Hostname:", hostname)
print("Location:", location)
print("Type:", device_type)

Debugging with Comments

Python comments are really useful when you’re trying to fix code that’s not working.

Disable Problematic Sections

When something’s broken, comment out parts to isolate the problem:

hostname = "SW1-ACCESS"
print("Device:", hostname)

# Turn this off temporarily to test
# vlan_id = 10
# print("VLAN:", vlan_id)

print("Script finished")

Add Debug Information

Stick in temporary comments to see what’s happening:

hostname = "SW1-ACCESS"
print("DEBUG: hostname is", hostname)  # Temporary debug line

device_type = "Switch"  
print("DEBUG: device_type is", device_type)  # Another debug line

Remember to remove debug comments when you’re done testing.

Break Down Complex Logic

Use comments to explain complicated bits:

# Check hostname follows our naming rules
# Should be: [Type][Number]-[Function]
# Like: SW1-ACCESS or R1-EDGE-RTR

if len(hostname) > 3:           # Must be at least 4 characters
    device_prefix = hostname[:2]  # First 2 characters
    if device_prefix in ["SW", "R1", "R2"]:  # Valid prefixes
        print("Hostname format OK")
    else:
        print("Bad device prefix")
else:
    print("Hostname too short")

Professional Comment Standards

Professional Python follows certain standards for comments. Worth knowing about even though you’re just learning.

PEP 8 Guidelines

Python has official style rules called PEP 8:

  • Use complete sentences in comments
  • Start with a capital letter
  • Two spaces before inline comments
  • Keep lines under 72 characters
# Good - follows the rules
hostname = "SW1-ACCESS"  # Primary building switch

# Bad - doesn't follow conventions
hostname = "SW1-ACCESS"# primary building switch

When Not to Comment

Sometimes code is clear enough that comments aren’t needed:

# Good - no comment needed
total_ports = 24
used_ports = 18
free_ports = total_ports - used_ports

# Bad - pointless comment
free_ports = total_ports - used_ports  # Subtract used from total

Real Examples

Let’s look at some proper examples of python comments in action.

Device Inventory Script

# device_inventory.py
# Keeps track of lab equipment
# Updated by network team

# All the devices in our lab
# Format: hostname -> IP address
lab_devices = {
    "SW1-ACCESS": "192.168.100.11",    # Building A switch
    "SW2-ACCESS": "192.168.100.12",    # Building B switch  
    "R1-EDGE-RTR": "192.168.100.1",    # Internet router
    "R2-CORE-RTR": "192.168.100.2"     # Internal router
}

# Show what we've got
print("Lab Equipment List")
print("=" * 20)

for hostname, ip_address in lab_devices.items():
    print(f"{hostname}: {ip_address}")

VLAN Configuration

# vlan_setup.py
# Configures VLANs according to company policy

# Standard VLAN assignments
# Sales: VLAN 10
# Engineering: VLAN 20
# Guests: VLAN 30
# Management: VLAN 99

vlans = {
    10: "Sales",         # Customer service team
    20: "Engineering",   # Technical team
    30: "Guest",         # Visitor access
    99: "Management"     # Infrastructure
}

# Create configuration commands
for vlan_id, vlan_name in vlans.items():
    print(f"vlan {vlan_id}")
    print(f" name {vlan_name}")

Network Calculations

# subnet_calc.py
# Basic network maths for our lab

# Our management network details
network_address = "192.168.100.0"  # Base network
subnet_mask = "255.255.255.0"      # /24 mask
prefix_length = 24                 # CIDR format

# Work out the numbers
# /24 gives us 254 usable addresses
# .0 is network, .255 is broadcast
# .1 to .254 are usable

total_addresses = 256      # 2^8 possible addresses
usable_addresses = 254     # Minus network and broadcast

print(f"Network: {network_address}/{prefix_length}")
print(f"Usable hosts: {usable_addresses}")

Making Comments Part of Your Process

Right, so here’s the key thing about python comments – they should be part of how you write code, not something you add afterwards.

When you’re planning a script:

  1. Write comments describing what you want to do
  2. Write code to implement each commented section
  3. Update comments if you change the approach
  4. Remove any temporary debug comments

Comments help you think through problems before you start coding. They force you to break down complex tasks into simple steps.

And here’s something most people don’t realize – good comments make debugging much easier. When something goes wrong, you can see exactly what each bit of code is supposed to do.

The time you spend writing good python comments will save you hours later when you’re trying to understand your own code. Trust me on this one.

Understanding comments properly is part of understanding how programming works. They’re not decorative – they’re an essential tool for writing code that you and others can actually understand and maintain.


External Link: PEP 8 Comment Guidelines – official Python style guide for writing good comments

1 thought on “Python for Network Engineers Blog 5: Python Comments”

  1. Pingback: Python for Network Engineers Blog 6: Python Indentation - RichardKilleen

Leave a Reply

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