Free tech learning for everyone, from basics to pro

Python for NetworkingProgramming and Application SecurityBeginner

Python basics for network engineers: install, run, variables, loops and if

In short: Python is the most common language for network automation because it is readable and has excellent networking libraries. You install Python 3, write a .py file, and run it from the terminal. Variables, if statements and loops are enough to start automating small, repetitive tasks.

Why Python for network work

Network engineers repeat the same jobs again and again: checking interfaces, building configuration, reading logs, auditing settings. Python is a general-purpose programming language that is easy to read, runs on Windows, macOS and Linux, and has mature libraries for talking to network devices and APIs (Application Programming Interfaces). You do not need to become a software developer. A few hundred lines of clear Python can save hours every week and reduce typing mistakes.

Always use Python 3. Python 2 reached end of life in 2020 and modern libraries no longer support it.

From idea to running scriptInstallPython 3 andan editorWritesave as .pyfileRunpython3script.pyRead outputerrors andresultsImprovesmall changes,rerun
Figure 1. Learning Python is a short loop: write a little, run it, read the result, then improve it.

Installing and running Python

  • Windows: install from the official installer or the Microsoft Store, and tick the option to add Python to PATH. Run scripts with py script.py.
  • macOS: install the official package or use a package manager such as Homebrew. Run with python3 script.py.
  • Linux: Python 3 is usually already installed. Check with python3 --version.

Use an editor that understands Python, such as VS Code with the Python extension. Typing python3 on its own opens the interactive shell (the REPL, read-evaluate-print loop), which is handy for testing one line at a time. Leave it with exit().

python3 --version
python3 hello.py

Variables, types and if statements

Core building blocksVariablesname a valueTypesstr, int, boolif / elifmake decisionsfor loopsrepeat over itemswhile loopsrepeat until doneprint / inputtalk to the user
Figure 2. Six building blocks cover most of the first scripts a network engineer writes.

A variable is a name that points to a value. Python works out the type for you. The types you will use most are strings (str) for text such as hostnames, integers (int) for numbers such as VLAN IDs, floats for decimals, and booleans (True/False). Indentation (four spaces) is not decoration in Python: it defines which lines belong to an if or a loop.

hostname = "core-sw1"
vlan_id = 20
uplink_up = True

if not 1 <= vlan_id <= 4094:
    print("Invalid VLAN ID")
elif vlan_id == 1:
    print("Avoid using VLAN 1 for user traffic")
else:
    print(f"{hostname}: VLAN {vlan_id} looks fine")

if uplink_up:
    print("Uplink is up")

The f"..." string is an f-string: anything inside braces is replaced by its value. It is the clearest way to build messages and configuration lines.

Loops: doing the same thing many times

A for loop repeats a block once for each item in a collection. A while loop repeats as long as a condition stays true. Most network scripts use for loops to walk through devices, interfaces or VLANs.

vlans = [10, 20, 30]
for vlan in vlans:
    print(f"vlan {vlan}")
    print(f" name USERS_{vlan}")

for port in range(1, 5):
    print(f"interface GigabitEthernet1/0/{port}")
    print(" switchport mode access")

attempts = 0
while attempts < 3:
    attempts += 1
    print(f"Attempt {attempts}")

Tip: range(1, 5) gives 1, 2, 3 and 4. The end value is not included, which catches out many beginners.

Common mistakes and good habits

  • Mixing tabs and spaces causes IndentationError. Set your editor to insert four spaces.
  • Comparing with =: use == to compare and = to assign.
  • Treating input as a number: input() always returns a string, so convert with int().
  • Hard-coding passwords: never put credentials in a script. Read them with getpass or from environment variables (covered in later notes).

At work, start with read-only scripts that generate configuration text or reports, review the output by eye, and only later move on to scripts that change devices. For exams and interviews, be ready to read a short script and say what it prints.

Practice

What does range(10, 13) produce?
The numbers 10, 11 and 12. The end value 13 is not included.
A script reads a VLAN with vlan = input("VLAN: ") and then checks vlan > 4094. What goes wrong?
input() returns a string, so comparing it with a number raises a TypeError. Convert first with int(vlan).
Why does indentation matter in Python?
It defines blocks. Lines indented under an if, for or while belong to that statement; wrong indentation changes the logic or causes an error.

Key takeaways

  • Use Python 3; run scripts with python3 (or py on Windows).
  • Variables hold values; the common types are str, int, float and bool.
  • if/elif/else make decisions; indentation defines the block.
  • for loops walk through collections; while loops repeat until a condition changes.
  • Never hard-code credentials; start with read-only, report-style scripts.
Tracks your learning on this device only. See your progress on the learning paths.

About the author

Mohamed Fayas

Founder of FM TecHub. CCNA certified, with a BTEC HND in Network Engineering, and BEng (Hons) in Computer Networking and Cloud Security. He writes practical, plain-English guides on networking, security and cloud.

More about the author

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Stay up to date by email

New notes, tools and security news from FM TecHub, explained simply. Free.

We only use your email to send these updates. See our privacy policy.