Python Indentation – Why This Will Drive You Mental At First
Right, so you’ve been writing some basic Python and you’ve probably noticed something weird. Python really cares about the spaces at the beginning of lines. Like, it’ll refuse to run your code if you get the spacing wrong.
Python for Network Engineers Blog 5: Python Comments
Coming from other programming stuff, this seems mental. Most languages use curly brackets or other symbols to group code together. Python just uses spaces. Seems a bit mad, doesn’t it?
But here’s the thing – you already understand python indentation perfectly. You just don’t know it yet.
You Already Know This
Look at any Cisco configuration:
interface GigabitEthernet0/1
description Sales Department
switchport mode access
switchport access vlan 10
See how the indented lines belong to the interface? That’s exactly how python indentation works. The spaces show which bits belong together.
Python just took this idea and made it part of the programming language. Brilliant, really.
How Python Does It
Instead of using brackets like other languages, Python uses indentation:
if device_status == "up":
print("Device is online")
print("Everything's working")
Those indented lines belong to the if statement. No brackets needed – the spacing tells Python what belongs where.
Compare that to how you’d write an interface config:
interface GigabitEthernet0/1
ip address 192.168.100.1 255.255.255.0
no shutdown
Same idea. The indented lines configure that interface.
The Rules (They’re Simple)
Python’s got a few rules about indentation. Get these wrong and your code won’t run.
Use Four Spaces
Don’t use tabs. Don’t use two spaces. Use four spaces for each level of indentation. That’s the Python way.
# Right - 4 spaces
if hostname == "SW1-ACCESS":
print("Main switch")
print("Building A")
Be Consistent
All lines at the same level need exactly the same indentation:
# Good
device_name = "SW1-ACCESS"
device_type = "Switch"
print(device_name)
# Bad - inconsistent spacing
device_name = "SW1-ACCESS"
device_type = "Switch" # Different indentation
print(device_name)
Python will throw a wobbly if you mix different indentation levels.
Don’t Mix Spaces and Tabs
This one’s evil because you can’t see it easily. You use spaces for one line, tabs for another. Looks fine to you, but Python has a complete meltdown.
Pick spaces. Stick with spaces. Always.
Common Ways to Mess This Up
Let me tell you the mistakes everyone makes with python indentation.
Indenting When You Shouldn’t
# Wrong - why are these indented?
print("Device check starting")
hostname = "SW1-ACCESS" # Shouldn't be indented
print(hostname) # Neither should this
Only indent when the line belongs to something above it.
Not Indenting When You Should
# Wrong - missing indentation
if device_status == "up":
print("Device online") # Should be indented
Python expects indented lines after that colon. No indentation, no worky.
Mixing Indentation Amounts
# Wrong - different amounts of indentation
if hostname == "SW1-ACCESS":
print("Two spaces") # 2 spaces
print("Four spaces") # 4 spaces
Pick an amount and stick with it. Four spaces is standard.
The Errors You’ll See
When you get python indentation wrong, Python tells you. Learning what these errors mean saves you loads of time.
IndentationError
if hostname == "SW1-ACCESS":
print("Main switch") # IndentationError: expected an indented block
Python expected indented lines but didn’t find any. Add four spaces before the print.
Unindent Doesn’t Match
if hostname == "SW1-ACCESS":
print("Main switch")
print("Status") # IndentationError: unindent does not match any outer indentation level
Your indentation levels don’t line up properly. Make sure lines at the same level use exactly the same spacing.
Mixed Tabs and Spaces
# TabError: inconsistent use of tabs and spaces
You’ve mixed tabs and spaces somewhere. Use only spaces.
Why This Actually Makes Sense
At first, python indentation seems like a pain. But it’s actually brilliant.
In other languages, you can write messy code that looks terrible but still works. Python forces you to format your code properly because the formatting IS the structure.
This means all Python code looks similar and is easy to read. You can pick up someone else’s Python code and understand it immediately because it follows the same visual structure.
Plus, you already think this way from network configurations. Interface commands are indented under the interface. VLAN commands are indented under the VLAN. Python just applies this to programming.
Real Examples
Let’s look at some actual python indentation in practice.
Basic Device Info
# Simple script - no indentation needed
print("Device Information")
hostname = "SW1-ACCESS"
location = "Building A"
print("Device:", hostname)
print("Location:", location)
Everything’s at the main level, so no indentation.
Device Status Check
print("Checking device status")
device_name = "SW1-ACCESS"
status = "online"
if status == "online":
print("Device responding") # Indented - belongs to if
print("Status: OK") # Indented - belongs to if
print("Check complete") # Back to main level
The indented lines only run if the device is online. The last line always runs.
Multiple Devices
print("Network Status Report")
# Device 1
device1 = "SW1-ACCESS"
if device1 == "SW1-ACCESS":
print("Switch 1: Online") # Belongs to first if
print("Location: Building A") # Belongs to first if
# Device 2
device2 = "R1-EDGE-RTR"
if device2 == "R1-EDGE-RTR":
print("Router 1: Online") # Belongs to second if
print("Location: Edge") # Belongs to second if
print("Report complete")
Each if statement has its own indented block.
Fixing Indentation Problems
When your python indentation goes wrong, here’s how to sort it out.
Read the Error Message
Python’s pretty good at telling you what’s wrong:
# IndentationError: expected an indented block
It expected indented lines but didn’t find them. Add indentation.
# IndentationError: unindent does not match any outer indentation level
Your indentation levels don’t match up. Fix the spacing.
Make Spaces Visible
Turn on “show whitespace” in your editor. Then you can see exactly what spaces and tabs you’re using.
Start Over
Sometimes it’s easier to delete the problematic bit and rewrite it with proper indentation rather than trying to fix what’s there.
Use a Proper Editor
Don’t use Notepad. Use something that helps with Python:
- IDLE (comes with Python)
- VS Code (free, excellent for Python)
- Notepad++ (free, shows whitespace)
These editors help you see indentation problems before they happen.
Setting Up Your Editor
Whatever you use to write Python, configure it properly:
IDLE Setup
Go to Format → Configure IDLE → General and set tab width to 4. Turn on line numbers too.
VS Code Setup
Install the Python extension. Set tab size to 4. Turn on “render whitespace” so you can see spaces.
The Key Settings
For any editor:
- 4 spaces for indentation
- Show whitespace characters
- Convert tabs to spaces automatically
- Show indentation guides
This prevents most problems before they start.
Building Good Habits
Start with good python indentation habits now and save yourself pain later.
Think About What Belongs Together
When you write code, think about which lines are related. Those lines should have the same indentation.
# These lines are all device setup - same level
hostname = "SW1-ACCESS"
device_type = "Switch"
location = "Building A"
# These lines check the device - would be indented if inside an if statement
# print("Checking device")
# print("Device online")
Indent As You Write
Don’t write everything then add indentation. Indent each line as you write it, based on what it belongs to.
Test Often
Run your code frequently. Python catches indentation errors immediately, so you can fix them before they become a bigger mess.
Why This Matters for Learning
Understanding python indentation is crucial because you’ll use it in everything else you learn about Python.
When we get to if statements (later), indentation shows which commands run conditionally. When we get to loops, indentation shows which commands repeat. When we get to functions, indentation shows which commands belong to the function.
But you don’t need to worry about that yet. For now, just understand that Python uses indentation to group related lines of code together.
It’s the same concept you use every day with network configurations. Python just made it part of the programming language.
The key thing is getting comfortable with the idea that spaces matter in Python. They’re not just for making code look nice – they’re part of how Python understands your code.
Get this right, and everything else becomes much easier. Get it wrong, and you’ll spend ages debugging indentation errors instead of learning programming.
But once you get used to it, python indentation becomes natural. It’s actually quite elegant – what you see is what you get. If it looks like lines belong together, they do.
External Link: PEP 8 Indentation Guidelines – official Python style guide for proper indentation practices
Pingback: Python for Network Engineers Blog 7: Python Variables - RichardKilleen