Python Print Function – Actually Understanding What You’re Doing
Right, so you’ve got Python installed and working and created your first scripts. Brilliant. Now let’s look at something you’ll use in every single Python program you write – the python print function.
Python for Network Engineers Blog 3: Your First Python Script
Now, I know what you’re thinking. “It’s just print, how complicated can it be?” Well, that’s exactly the attitude that gets network engineers into trouble when they’re learning programming. They think print is just for displaying text, miss all the useful features, then wonder why their code looks messy and doesn’t work properly.
The python print function is actually your main tool for getting information out of your programs. When you’re learning Python fundamentals, print is how you see what’s happening inside your code. When you’re working with network data, print is how you display device information, configuration details, and results.
But here’s the thing – most Python tutorials teach print using completely pointless examples. Student names, shopping lists, that sort of rubbish. No wonder network engineers get confused about how print actually helps with real work.
Let’s do this properly, using examples that make sense for people who understand networks.
What the Python Print Function Actually Does
Okay, so let’s start with the basics. The python print function takes whatever you give it and displays it on the screen. Simple enough, right?
print("Hello")
That displays “Hello” on the screen. But here’s what’s actually happening under the hood, and this matters for understanding Python fundamentals.
When you call print, Python converts whatever you give it into text, then sends that text to what’s called “standard output” – normally your screen. Print always adds a newline character at the end, so the next thing you print appears on a new line.
print("SW1-ACCESS")
print("SW2-ACCESS")
Gives you:
SW1-ACCESS
SW2-ACCESS
Two separate lines, because print automatically adds that newline.
Now, why does this matter for network engineers? Because when you’re working with device information, configuration data, or command outputs, you need to understand exactly how print formats and displays information. Get the formatting wrong, and your output becomes unreadable.
Print vs Return – Understanding the Difference
Here’s something that confuses a lot of people learning Python. There’s a difference between print and return, and understanding this difference is crucial for Python fundamentals.
Print displays something on the screen. That’s it. It doesn’t give the value back to your program.
Return (which we’ll cover properly when we get to functions) gives a value back to your program, but doesn’t display anything.
# This prints to screen but doesn't give value back
print("R1-EDGE-RTR")
# Later, when we cover functions, return gives value back
# def get_hostname():
# return "R1-EDGE-RTR" # Gives value back, doesn't print
For now, just remember that print is for displaying information, not for passing values around inside your program.
Basic Python Print Function Usage
Let’s look at the different ways you can use the python print function with networking examples that actually make sense.
Printing Text Directly
The simplest use of print is displaying text directly:
print("Device configuration backup completed")
print("VLAN 10 configured successfully")
print("Interface GigabitEthernet0/1 is up")
The text you want to print goes inside quotes. You can use either single quotes or double quotes, doesn’t matter which:
print("Using double quotes")
print('Using single quotes')
Both work exactly the same way. Pick one style and stick with it. Most people use double quotes, but it’s your choice.
Printing Variables
More useful than printing text directly is printing the contents of variables:
hostname = "SW1-ACCESS"
print(hostname)
This displays “SW1-ACCESS” because that’s what’s stored in the hostname variable.
You can print different types of data:
device_name = "R1-EDGE-RTR" # String
vlan_id = 10 # Integer
cpu_usage = 23.7 # Float
interface_up = True # Boolean
print(device_name) # R1-EDGE-RTR
print(vlan_id) # 10
print(cpu_usage) # 23.7
print(interface_up) # True
Python automatically converts these different data types to text when printing them. You don’t have to worry about conversion – print handles it.
Printing Multiple Things at Once
You can print multiple items in a single print statement by separating them with commas:
hostname = "SW1-ACCESS"
ip_address = "192.168.100.11"
vlan = 10
print(hostname, ip_address, vlan)
This gives you:
SW1-ACCESS 192.168.100.11 10
Notice how Python automatically puts spaces between the items. That’s the default behaviour of the python print function when you give it multiple arguments.

Understanding Print Function Parameters
Right, so here’s where the python print function gets more interesting. Print has several optional parameters that control how it formats output. These parameters are part of the PCEP syllabus, so you need to understand them properly.
The full signature of print looks like this:
print(*values, sep=' ', end='\n', file=sys.stdout, flush=False)
That looks complicated, but it’s actually straightforward. Let’s break it down using networking examples.
The sep Parameter
The sep parameter controls what goes between items when you print multiple things. By default, it’s a space, but you can change it:
hostname = "SW1"
location = "Building A"
floor = "Floor 2"
# Default separator (space)
print(hostname, location, floor)
# Output: SW1 Building A Floor 2
# Custom separator
print(hostname, location, floor, sep="-")
# Output: SW1-Building A-Floor 2
# No separator
print(hostname, location, floor, sep="")
# Output: SW1Building AFloor 2
# Tab separator
print(hostname, location, floor, sep="\t")
# Output: SW1 Building A Floor 2
This is really useful when you’re formatting network information. Instead of manually adding separators, let print do it for you:
device = "R1-EDGE-RTR"
interface = "GigabitEthernet0/1"
status = "up"
protocol = "up"
print(device, interface, status, protocol, sep=" | ")
# Output: R1-EDGE-RTR | GigabitEthernet0/1 | up | up
Much cleaner than trying to build the string manually.
The end Parameter
The end parameter controls what print adds at the end of the output. By default, it’s a newline character (\n), which is why each print statement appears on a new line.
# Default behaviour - each print on new line
print("VLAN 10")
print("VLAN 20")
print("VLAN 30")
Gives you:
VLAN 10
VLAN 20
VLAN 30
But you can change this:
# Print on same line with space
print("VLAN 10", end=" ")
print("VLAN 20", end=" ")
print("VLAN 30")
Gives you:
VLAN 10 VLAN 20 VLAN 30
Or use different end characters:
print("Device:", end=" ")
print("SW1-ACCESS")
# Output: Device: SW1-ACCESS
print("Checking interface", end="...")
print("Done")
# Output: Checking interface...Done
This is particularly useful when you want to build up output gradually or create progress indicators.
Combining sep and end Parameters
You can use both parameters together for precise control over formatting:
devices = ["R1-EDGE-RTR", "R2-CORE-RTR", "SW1-ACCESS"]
print("Network devices:", end=" ")
print(devices[0], devices[1], devices[2], sep=", ", end=".\n")
# Output: Network devices: R1-EDGE-RTR, R2-CORE-RTR, SW1-ACCESS.
String Formatting with Print
Right, so we’ve covered the basic python print function usage. Now let’s look at more advanced formatting techniques that make your output cleaner and more professional.
F-strings – The Modern Way
The best way to format strings in modern Python is using f-strings (formatted string literals). Put an f before your string, then use curly braces to insert variables:
hostname = "SW1-ACCESS"
ip_address = "192.168.100.11"
port_count = 24
print(f"Device {hostname} at {ip_address} has {port_count} ports")
# Output: Device SW1-ACCESS at 192.168.100.11 has 24 ports
Much cleaner than concatenating strings manually or using old-style formatting.
You can include expressions inside the curly braces:
total_ports = 48
used_ports = 23
print(f"Port utilization: {used_ports}/{total_ports} ({used_ports/total_ports*100:.1f}%)")
# Output: Port utilization: 23/48 (47.9%)
The :.1f part formats the number to one decimal place. F-strings give you lots of formatting options.
Formatting Numbers
When working with network data, you often need to format numbers properly:
cpu_usage = 15.7234
memory_usage = 0.4567
bandwidth = 1000000000
print(f"CPU: {cpu_usage:.1f}%") # CPU: 15.7%
print(f"Memory: {memory_usage:.1%}") # Memory: 45.7%
print(f"Bandwidth: {bandwidth:,} bps") # Bandwidth: 1,000,000,000 bps
Different format codes give you different number presentations:
:.1f– floating point with 1 decimal place:.1%– percentage with 1 decimal place:,– thousands separator:>10– right-aligned in 10 characters:<10– left-aligned in 10 characters
Formatting Tables
F-strings are excellent for creating aligned output that looks like tables:
devices = [
("SW1-ACCESS", "192.168.100.11", "24"),
("SW2-ACCESS", "192.168.100.12", "48"),
("R1-EDGE-RTR", "192.168.100.1", "4")
]
print(f"{'Device':<12} {'IP Address':<15} {'Ports':<6}")
print("-" * 35)
for device, ip, ports in devices:
print(f"{device:<12} {ip:<15} {ports:<6}")
Output:
Device IP Address Ports
-----------------------------------
SW1-ACCESS 192.168.100.11 24
SW2-ACCESS 192.168.100.12 48
R1-EDGE-RTR 192.168.100.1 4
The :<12 means left-aligned in a field 12 characters wide. Very useful for creating readable output.

Common Python Print Function Mistakes
Let me tell you about the mistakes I see network engineers make when learning the python print function. Understanding these helps you avoid confusion and write better code.
Mistake 1: Forgetting Quotes Around Text
# Wrong - Python thinks SW1-ACCESS is a variable name
print(SW1-ACCESS) # NameError
# Right - quotes make it a string
print("SW1-ACCESS") # Works fine
If you want to print literal text, it needs quotes. If you want to print a variable’s contents, no quotes.
Mistake 2: Mixing Up Variables and Strings
hostname = "R1-EDGE-RTR"
# Wrong - this prints the word "hostname", not the variable's value
print("hostname") # Output: hostname
# Right - this prints the variable's value
print(hostname) # Output: R1-EDGE-RTR
# Right - this includes both
print("Hostname:", hostname) # Output: Hostname: R1-EDGE-RTR
Mistake 3: Not Understanding Print’s Return Value
hostname = "SW1-ACCESS"
result = print(hostname) # Prints SW1-ACCESS to screen
print(result) # Prints None
# Print doesn't return the value, it just displays it
# result contains None, not "SW1-ACCESS"
Print always returns None. If you want to both display and store a value, you need to do them separately.
Mistake 4: Overcomplicating Simple Output
device = "SW1-ACCESS"
vlan = 10
# Overcomplicated
print("Device " + str(device) + " is in VLAN " + str(vlan))
# Much simpler with f-strings
print(f"Device {device} is in VLAN {vlan}")
F-strings handle the type conversion automatically. Don’t make it harder than it needs to be.
Advanced Print Function Techniques
Right, let’s look at some more advanced uses of the python print function that come in handy when working with network data.
Printing to Files
By default, print sends output to the screen. But you can redirect it to files using the file parameter:
hostname = "SW1-ACCESS"
config = "vlan 10\n name Sales"
# Print to a file instead of screen
with open("device_config.txt", "w") as config_file:
print(f"Configuration for {hostname}:", file=config_file)
print(config, file=config_file)
This creates a file with your print output instead of displaying it on screen. Useful for logging or creating reports.
The flush Parameter
Sometimes you want to ensure print output appears immediately, especially when creating progress indicators:
import time
print("Connecting to device", end="")
for i in range(5):
print(".", end="", flush=True)
time.sleep(1)
print(" Connected!")
The flush=True forces Python to display the dots immediately instead of waiting for the line to complete.
Printing Special Characters
Network data sometimes contains special characters that need careful handling:
# Newlines and tabs
print("Line 1\nLine 2\tTabbed")
# Output:
# Line 1
# Line 2 Tabbed
# Backslashes (common in file paths)
print("Path: C:\\Network\\Configs\\")
# Output: Path: C:\Network\Configs\
# Quotes inside strings
print('Device description: "Main office switch"')
print("Device name: 'SW1-ACCESS'")
Use \n for newlines, \t for tabs, \\ for backslashes, and alternate quote types to include quotes in your text.
Debugging with Print
One of the most important uses of the python print function when learning programming is debugging – figuring out what your code is actually doing.
Checking Variable Values
When your code isn’t working as expected, use print to see what’s in your variables:
hostname = "SW1-ACCESS"
vlan_id = 10
description = "Sales Department"
# Check what's actually stored
print("hostname contains:", hostname)
print("vlan_id contains:", vlan_id)
print("description contains:", description)
This shows you exactly what data your variables contain, which helps spot problems.
Tracking Program Flow
Use print to see which parts of your code are actually running:
device_status = "up"
print("Checking device status...")
if device_status == "up":
print("Device is up - proceeding with configuration")
# Configuration code would go here
else:
print("Device is down - skipping configuration")
print("Status check complete")
This shows you which branches of your code execute, helping you understand program flow.
Displaying Intermediate Results
When doing calculations or data processing, print intermediate steps:
total_ports = 48
used_ports = 23
print(f"Total ports: {total_ports}")
print(f"Used ports: {used_ports}")
free_ports = total_ports - used_ports
print(f"Free ports calculation: {total_ports} - {used_ports} = {free_ports}")
utilization = (used_ports / total_ports) * 100
print(f"Utilization calculation: ({used_ports} / {total_ports}) * 100 = {utilization}")
This helps you verify each step of your calculations.
Print Function Best Practices
Here’s what I’ve learned about using the python print function effectively after years of writing Python code and teaching it to network engineers.
Be Descriptive with Output
Don’t just print values – explain what they are:
# Poor
print(cpu_usage) # Just prints a number
# Better
print(f"CPU usage: {cpu_usage}%") # Clear what the number means
Use Consistent Formatting
Establish formatting patterns and stick to them:
# Consistent status messages
print(f"[INFO] Device {hostname} is online")
print(f"[WARN] High CPU usage on {hostname}: {cpu_usage}%")
print(f"[ERROR] Cannot connect to {hostname}")
Don’t Overuse Print for Debugging
It’s tempting to add print statements everywhere when debugging. But too many prints make output hard to read. Add them strategically, then remove them when done.
Consider Your Audience
If other people will see your program’s output, make it clear and professional:
# For debugging (you only)
print("dbg: vlan_id =", vlan_id)
# For users (others might see)
print(f"VLAN {vlan_id} configured successfully")
Understanding Output vs Side Effects
This is an important concept for Python fundamentals that often confuses beginners. The python print function is what we call a “side effect” – it does something (displays text) but doesn’t produce a value that your program can use.
# print() is a side effect - it displays text but returns None
result = print("Hello")
print(result) # Prints: None
# Variables store values - they don't have side effects
hostname = "SW1-ACCESS" # Stores a value
print(hostname) # Side effect: displays the value
Understanding this distinction helps you think clearly about what your code is doing versus what it’s displaying.
Real-World Print Examples
Let’s look at some realistic examples of using the python print function for network-related tasks. These aren’t automation scripts – they’re simple programs that demonstrate print fundamentals.
Device Inventory Display
# Simple device inventory
devices = [
("R1-EDGE-RTR", "192.168.100.1", "Router"),
("SW1-ACCESS", "192.168.100.11", "Switch"),
("SW2-ACCESS", "192.168.100.12", "Switch")
]
print("Network Device Inventory")
print("=" * 30)
for hostname, ip, device_type in devices:
print(f"{hostname:<15} {ip:<15} {device_type}")
Configuration Status Report
# Configuration status for multiple VLANs
vlans = [10, 20, 30, 99]
statuses = ["Active", "Active", "Inactive", "Active"]
print("VLAN Status Report")
print("-" * 20)
for vlan, status in zip(vlans, statuses):
status_indicator = "✓" if status == "Active" else "✗"
print(f"VLAN {vlan:>3}: {status:<8} {status_indicator}")
Port Utilization Summary
# Port utilization across multiple switches
switches = {
"SW1-ACCESS": {"total": 24, "used": 18},
"SW2-ACCESS": {"total": 48, "used": 23},
"SW3-DIST": {"total": 24, "used": 12}
}
print("Port Utilization Summary")
print("=" * 40)
print(f"{'Switch':<12} {'Used':<6} {'Total':<6} {'Util%':<6}")
print("-" * 40)
for switch, ports in switches.items():
used = ports["used"]
total = ports["total"]
utilization = (used / total) * 100
print(f"{switch:<12} {used:<6} {total:<6} {utilization:>5.1f}%")
These examples show practical uses of print formatting without getting into complex automation concepts.
Troubleshooting Print Issues
When the python print function doesn’t work as expected, here are the common problems and solutions:
Nothing Appears on Screen
If print doesn’t seem to work:
# Check you're actually calling print
hostname = "SW1-ACCESS"
hostname # This doesn't print anything in a script
# You need to explicitly call print
print(hostname) # This works
Unexpected Output Format
# If output looks wrong, check your data types
port_count = "24" # String, not number
vlan_id = 10 # Number
print(f"Device has {port_count} ports on VLAN {vlan_id}")
# Works, but port_count is text, not a number for calculations
Encoding Issues with Special Characters
If you see weird characters in output:
# Use UTF-8 encoding for international characters
print("Device location: Düsseldorf") # Might cause issues
# Usually works fine in modern Python, but be aware of encoding
The python print function is fundamental to learning Python programming. It’s your main tool for seeing what’s happening in your code, displaying results, and debugging problems. Master print properly, and you’ll write cleaner, more readable Python programs.
You understand how print works, its parameters, formatting options, and practical applications. This knowledge forms the foundation for everything else you’ll learn about Python output and program interaction.
External Link: Python Print Function Documentation – official Python documentation for the print function

Pingback: Python for Network Engineers Blog 5: Python Comments - RichardKilleen