Skip to content
Home » Blog » Python for Network Engineers Blog 9: Python Integers

Python for Network Engineers Blog 9: Python Integers

Main blog image for Python for Network Engineers Blog 9: Python Integers, showing Python code calculating interface up percentage on a network switch

Python Integers – Actually, Let’s Sort This Out Properly

Okay so we’re at python integers now. So we’ve got variables working haven’t we, got the print function sorted, comments are done, you’ve figured out the indentation business.

Right so integers. Now this is where it gets mental again because most Python courses, they’ll have you doing the most ridiculous things with integers. Counting apples, working out people’s ages, calculating mortgage payments. I’m sitting there thinking, hang on mate, I need to work with VLAN numbers and port counts. How’s Dave’s age going to help me configure a switch stack then?

Python for Network Engineers Blog 8: Python Strings

Look, I’ll tell you what happened to me. About three years back, kept hearing about this Python stuff. Boss mentioned it a few times. Saw job adverts asking for “scripting experience” and thought bollocks, now what?

So I had a look at some Python courses. First one I tried, they’re teaching me to make a calculator. I’m thinking how’s this going to help me configure VLANs then? Spoiler alert – it doesn’t.

Gave up after about a week. Complete waste of time.

Few months later, had this massive project. Forty-odd switches needed the same VLAN setup. Thought there’s got to be a better way than SSH-ing into each one and copy-pasting configs all day.

Found a different Python course, this one actually used networking examples. Made much more sense straight away. Instead of learning about storing someone’s name in a variable, I’m learning about storing hostnames. Instead of calculating mortgage payments, I’m working with IP addresses and VLAN IDs.

So anyway, let’s do integers properly using network stuff that matters.

What Are Integers Then

Right so an integer in Python, it’s just a whole number isn’t it. No decimal points, no fractions, just complete numbers. Could be positive, negative, zero, doesn’t matter.

vlan_id = 10
port_count = 24
routing_metric = 100

See? Actual networking numbers. Not how many pets Dave’s got.

Now here’s something I didn’t know when I started. Python integers, they can be absolutely massive. Like, stupidly big. Most programming languages, they make you worry about different integer sizes. 8-bit integers, 16-bit integers, 32-bit integers, all with different limits. Pain in the backside.

Python just says forget all that nonsense. Integer’s an integer, it’ll grow as big as your memory allows. Brilliant for networking where you might be dealing with enormous numbers.

Actually had this come up last year. Working with some autonomous system numbers that were way bigger than normal 32-bit integers could handle. Python didn’t even blink. Just worked perfectly.

Why This Matters for Network Stuff

Look, networking’s absolutely stuffed with numbers, right? VLAN IDs, port numbers, interface speeds, routing metrics, subnet sizes. Everything’s got numbers attached.

Understanding integers properly means you can work with all this numerical data without constantly converting between text and numbers. Makes your scripts much cleaner.

management_vlan = 99
sales_vlan = 10
eng_vlan = 20

These are integers because they represent actual countable things. Can’t have VLAN 10.5 can you? Doesn’t make sense.

But here’s where people get confused. When should network information be integers versus strings?

When to Use Integers vs Strings

This catches people out constantly. When should you store network information as integers versus strings?

Simple rule I use. If you need to do maths with it, make it an integer. If it’s just an identifier, keep it as a string.

vlan_id = 10              # Integer - might need calculations
hostname = "SW1-ACCESS"   # String - just an identifier

So vlan_id = 10 as an integer because you might need to calculate ranges or compare values. But hostname = “SW1-ACCESS” as a string because it’s just a text identifier.

Split screen blog image comparing VLAN IDs as python integers and hostnames as strings in Python for network engineers

IP addresses are bit tricky though. Most of the time you’ll handle them as strings because you’re not doing arithmetic on the actual address. But if you’re doing subnet calculations or need to work with address ranges, you might convert them temporarily.

Got caught out by this early on actually. Had a script that was storing VLAN IDs as strings, couldn’t work out why my range calculations weren’t working. Spent ages debugging before I realised I was trying to do maths on text. Felt like a right pillock.

The key thing is thinking about what you’re actually going to do with the data. Calculations and comparisons need integers. Everything else can probably stay as strings.

Different Number Systems We Actually Use

Right so here’s something that confused the hell out of me when I started. Networking uses different number systems all the time, but Python needs to know which one you mean.

Decimal’s what you’re used to. Normal counting, base 10. That’s Python’s default.

vlan_id = 10
subnet = 24

Nothing special there.

But we use other systems constantly don’t we?

Binary’s everywhere in networking. Subnet masks, access lists, thinking about individual bits when you’re working with routing protocols. Python handles binary with 0b at the start.

subnet_mask = 0b11111111111111111111111100000000  # /24 mask

That’s a /24 mask in binary. Python converts it to decimal automatically when you need to use it. Most of the time you won’t write binary directly, but understanding it helps when you’re working with subnetting or access control where you need to think in terms of individual bits.

Hex shows up constantly too. MAC addresses, router IDs, memory addresses when you’re debugging stuff. Python uses 0x prefix.

mac_oui = 0x001122    # First part of MAC address

Don’t use octal much in modern networking, but you’ll see it in file permissions sometimes. Python uses 0o prefix.

file_permissions = 0o755     # Octal permissions

Honestly rarely use it these days, but worth knowing about because you’ll run into it occasionally.

The important bit is Python can handle all these different formats, so when you’re parsing configuration files or working with protocol data that uses different number representations, Python sorts it out for you.

Working with Integer Variables

Let me tell you about mistakes I see people make constantly when working with integers. Made most of these myself at some point.

Keep it simple when creating variables. If you know it’s an integer, just assign it.

vlan_sales = 10
vlan_eng = 20

Don’t do daft things like vlan_sales = int(“10”). Why convert from string if you already know it’s the number 10?

Python integers work perfectly for network calculations.

total_ports = 48
used_ports = 23
free_ports = total_ports - used_ports

Basic arithmetic that actually means something.

The double slash // is integer division. Gives whole numbers without decimals. Perfect for clean percentage calculations where you don’t want decimal places cluttering up your output.

Integer comparisons are crucial for network validation too.

if vlan_id < 1 or vlan_id > 4094:
    print("Invalid VLAN")

Basic validation that prevents configuration errors before they happen.

Mistakes Everyone Makes

Right, let me tell you about cock-ups I see repeatedly. Made most of these myself when I was learning.

Big one is treating numbers as text. Storing numbers as strings then trying to calculate with them.

# Wrong
vlan_1 = "10"
vlan_2 = "20"
total = vlan_1 + vlan_2  # Gets "1020" not 30!

# Right
vlan_1 = 10
vlan_2 = 20
total = vlan_1 + vlan_2  # Gets 30

Happens because the plus operator joins strings instead of adding numbers. Took me ages to figure this out the first time it happened.

The input() function always returns strings, even if the user types a number. Need to convert before doing maths.

port_input = input("Port number: ")
port_number = int(port_input) + 1

Not handling bad input properly bit me badly once. User entered rubbish, script crashed in front of the entire network team. Proper embarrassing that was.

try:
    vlan_id = int(user_input)
except ValueError:
    print("Must be a number")

Always use try/except when converting strings to integers. If the conversion fails, handle it gracefully instead of letting your script explode.

Code editor screenshot showing common python integer mistakes with error messages, demonstrating string concatenation vs integer addition

Python has two division operators and they behave differently. Single slash / gives decimals, double slash // gives integers. Choose the right one depending on what you need.

Actually Useful Applications

Once you get integers sorted, loads of networking tasks become much easier.

For VLAN management, define your ranges once then reference them throughout your scripts.

data_vlan_start = 10
data_vlan_end = 99

# Check if VLAN is in data range
if data_vlan_start <= test_vlan <= data_vlan_end:
    print("Data VLAN")

Then you can check if any given VLAN falls within your data range without remembering specific numbers.

Capacity planning becomes straightforward.

users_per_floor = 24
floors = 4
growth_factor = 20  # 20% growth allowance

total_users = users_per_floor * floors
switches_needed = (total_users + 47) // 48  # Round up

Work out total users, add growth allowance, divide by ports per switch. Round up to get the number of switches needed. Much more reliable than guessing.

Basic subnet calculations using powers of 2.

prefix_length = 24
host_bits = 32 - prefix_length
usable_addresses = (2 ** host_bits) - 2

This kind of calculation comes up constantly when you’re planning IP addressing schemes.

Converting Between Number Systems

Sometimes you need to convert between decimal, binary, hex when working with different configuration formats.

vlan_id = 255
binary_vlan = bin(vlan_id)    # '0b11111111'
hex_vlan = hex(vlan_id)       # '0xff'

Converting back to decimal:

decimal_value = int("ff", 16)  # Convert hex to decimal

Useful when you’re parsing configuration files that use different representations or when you’re working with protocol data that comes in various formats.

Python terminal output showing the number 255 displayed as decimal, binary, and hexadecimal using networking variable names

Real Network Examples

Let me show you actual scenarios where integer handling matters.

Port counting across your entire network.

switch_ports = {
    "SW1-ACCESS": 24,
    "SW2-ACCESS": 48,
    "SW3-DIST": 24
}

total_ports = sum(switch_ports.values())
used_ports = 67
utilization = (used_ports * 100) // total_ports
print(f"Network utilization: {utilization}%")

Much more accurate than trying to keep track manually.

VLAN allocation tracking.

allocated_vlans = [10, 20, 30, 99]
next_vlan = 1

while next_vlan in allocated_vlans:
    next_vlan += 1

print(f"Next available VLAN: {next_vlan}")

Automatically finds the next available VLAN instead of hunting through configurations manually.

Bandwidth calculations.

interface_speeds = {
    "FastEthernet": 100,
    "GigabitEthernet": 1000,
    "TenGigE": 10000
}

total_bandwidth = 4 * interface_speeds["TenGigE"]
print(f"Backbone: {total_bandwidth}Mbps")

The maths is straightforward once you’re comfortable with integer arithmetic.

Division Behaviour Worth Understanding

Python division behaves differently depending on which operator you use.

bandwidth = 1000
devices = 3

float_division = bandwidth / devices      # 333.333...
integer_division = bandwidth // devices   # 333
remainder = bandwidth % devices          # 1

Choose the right operator for what you need.

This comes up constantly in network calculations. Fair bandwidth allocation, working out how many devices you can fit in racks, calculating port utilization percentages. Understanding which division operator to use saves confusion later.

Large Numbers and Python

Python handles massive numbers without any problems.

ipv4_addresses = 2 ** 32
ipv6_addresses = 2 ** 128  # Enormous number

print(f"IPv4 space: {ipv4_addresses:,}")
print(f"IPv6 is much larger: {ipv6_addresses > ipv4_addresses}")
vs code snipped showing how python intergers can be used for ipv4 and ipv6 addresses
IPv4 addresses as shown are over 4 billion addresses:

IPv6 however is estimated to have the same amount of unique addresses than Atoms in 6.775 gigatonnes of Carbon

Useful for address space calculations or when working with large autonomous system numbers.

Had this come up recently actually. Working with some BGP route calculations that involved numbers way bigger than traditional programming languages can handle. Python just sorted it out without me having to worry about special data types or overflow errors.

Why This All Actually Matters

Understanding python integers properly is fundamental to everything else you’ll do with network automation. Variables, loops, functions, data structures – they all build on these basic concepts.

Get integers wrong and you’ll spend ages debugging weird calculation errors. Get them right and automation becomes much more straightforward.

The key thing is using integers for actual numerical network data. VLAN IDs, port counts, interface speeds, routing metrics. Not abstract programming exercises that don’t help anyone.

When you’re working with network protocols, configurations, capacity planning, all the maths becomes much easier once you’re comfortable with integer operations and conversions.

That’s integers sorted properly. You understand what they are, how they work with networking data, common mistakes to avoid, and practical applications for real network engineering tasks. Much more useful than learning about theoretical mathematical problems that have nothing to do with your actual job.


External Link: Python Integer Documentation – official Python documentation for integer operations and methods

1 thought on “Python for Network Engineers Blog 9: Python Integers”

  1. Pingback: Python for Network Engineers Blog 10: Python Floats - RichardKilleen

Leave a Reply

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