Python for Network Engineers ยท Python from zero

Python 1: print, variables, strings & f-strings

Your first real Python: show things with print, store values in variables, clean up text with string methods, and build config lines with f-strings. Then fix a broken script by reading its errors one by one.

31 min read9 chapters2 labs15 quiz7 scenarios15 interview Q&A

This first module is free: read the lesson and take the quiz. Create a free account to run up to 3 hands-on labs.

Log inStart free
Jump to chapter (9)
01

Python 1: what you will learn and the big picture

What you will learn. This module teaches the very first building blocks of Python, one small idea per chapter: showing text with print, storing values in variables, the difference between text and numbers, cleaning text with string methods, building configuration lines with f-strings, yes/no values called booleans, and how to read and fix the three errors every beginner meets. You do not need any programming background. If you finished the module "What is network automation?", you have already run a script; here you learn to write the lines yourself.

Prerequisites. Basic networking: interface names such as GigabitEthernet0/1, VLAN numbers and IP addresses. Everything in this module runs on the lab host AUTO; no routers are needed.

Analogy: labelled jars and a mail-merge letter

Picture a kitchen shelf with jars. Each jar has a label (salt, sugar) and something inside. A variable is a jar: a name on the outside, a value inside. Now picture a printed letter that says "Dear ____, your VLAN is ____". A clerk fills the blanks from a list. That is an f-string: a sentence with blanks that Python fills from your jars. Together they let one small script produce the exact configuration for any port, any VLAN, any site.

Valueshostname, vlanVariablesnamed jarsf-stringtemplate + jarsConfig textready to paste

The pipeline of this module: values go into variables, an f-string fills a template, config text comes out.

A first look at the lab script

In Lab 1 you get hello_router.py. Read it now even if you do not understand every word yet; by chapter 6 you will understand all of it. Lines starting with # are comments.

# hello_router.py - build interface config lines with Python
# A VARIABLE is a named box that stores a value.
interface = "GigabitEthernet0/1"   # a string (text): always inside quotes
vlan = 10                          # an integer (whole number): no quotes
site = "  pune  "                  # messy text with extra spaces

# print() shows something on the screen
print("Building config...")

# .strip() removes spaces at both ends, .upper() makes CAPITAL letters
clean_site = site.strip().upper()

# f-string: put f before the quote, then {name} is replaced by its value
print(f"interface {interface}")
print(f" description Link to {clean_site} - VLAN {vlan}")
print(" switchport mode access")
print(f" switchport access vlan {vlan}")
AUTO> python3 hello_router.py
Building config...
interface GigabitEthernet0/1
 description Link to PUNE - VLAN 10
 switchport mode access
 switchport access vlan 10

Five short lines of output came from seventeen lines of script. Change one variable, say vlan = 20, and the text changes with it. You never retype the configuration.

The eight chapters ahead

  1. print and comments
  2. Variables
  3. Strings, integers and types
  4. String methods
  5. f-strings
  6. Numbers, maths and booleans
  7. Fixing errors (the report lab)
  8. Summary and checklist

Worked example. Without Python you would type description Link to PUNE - VLAN 10 for each port, changing site and VLAN by hand 48 times on a stack. With Python you write the sentence once and let the variables change.

Common mistake. Trying to memorise syntax. Programmers look things up all the time. Aim to understand the idea; the exact spelling comes with practice, and Python tells you when you slip.

Exam trap. The 350-901 exam shows short Python snippets and asks what they print, or what is wrong with them. Being able to read variables, strings and f-strings quickly is the foundation for every later question.

The 48-port switch stack

A branch needed 48 access ports labelled with a site name and a VLAN. An engineer who knew only the CLI typed 48 descriptions and mixed up two VLANs. A colleague wrote a seven-line Python script with a site variable and a VLAN variable and printed all 48 correct descriptions in one run, which the first engineer then pasted into the switch.

Lesson: variables plus a template turn repetition into one reviewed line.

"Why do network engineers generate configuration text with a script?"

Because configuration is mostly the same pattern with a few values that change. A script keeps the pattern in one place and fills the changing values from variables, so output is consistent, quick to produce and easy to review. It also avoids copy-and-paste mistakes.

Key takeaways

  • A variable is a named jar holding a value; an f-string fills a template from your jars.
  • This module runs entirely on the AUTO host; no routers needed.
  • One small idea per chapter: print, variables, types, methods, f-strings, booleans, errors.
  • Errors are normal and Python explains them.
02

print() and comments

Every script needs a way to show something to you. In Python that is print(). It is like the show command: it displays information on the screen so that you can read it. This chapter teaches print and the comment, the two simplest tools you will use in every script.

print() shows what is in the brackets

print("Hello, router")
print("VLAN", 10)
print("Gi0/1", "is", "up")
print()
print("end")
AUTO> python3 p1.py
Hello, router
VLAN 10
Gi0/1 is up

end
  • Text goes inside quotes. Single or double quotes both work. The quotes are not printed.
  • A number needs no quotes: 10.
  • Several things separated by commas are printed with one space between them.
  • print() with nothing inside prints an empty line, handy to space out a report.

Quotes inside text

If your text contains a quote mark, choose the other kind around it. Python also understands special characters written with a backslash: \n means "new line" and \t means "tab".

print("It's up")
print('Description "Core link"')
print("line one\nline two")
print("a\tb")
AUTO> python3 p2.py
It's up
Description "Core link"
line one
line two
a	b

Two options of print are worth knowing. sep changes the separator between items and end changes what is printed at the very end (normally a new line):

print("a", "b", "c", sep="-")
print("no newline", end="")
print(" <- same line")
AUTO> python3 p3.py
a-b-c
no newline <- same line

Comments: notes for humans

A comment starts with #. Python ignores the rest of that line. Use comments to say why a line exists. A comment can sit on its own line or at the end of a code line. Good scripts are readable months later because of comments.

# This whole line is a comment: Python skips it.
print("Report start")   # a comment at the end of a code line
# print("this line is switched off")
print("Report end")
AUTO> python3 p4.py
Report start
Report end

The third line shows a useful trick: putting # in front of a line "switches it off" without deleting it. Programmers call this commenting out.

The classic first error

If you open a quote and forget to close it, Python cannot read the file at all. It reports a SyntaxError before running anything:

print("Hello)
AUTO> python3 p5.py
  File "p5.py", line 1
    print("Hello)
          ^
SyntaxError: unterminated string literal (detected at line 1)

Read it from the bottom: SyntaxError: unterminated string literal means a piece of text has no closing quote. The small ^ arrow points at where Python noticed the problem.

Worked example. A config generator prints a small banner first: print("=== Config for PUNE ==="), then a blank print(), then the lines. Banners and blank lines make long outputs easy to scan.

Common mistake. Mixing curly "smart quotes" copied from a document or chat with normal straight quotes. Python only understands straight quotes " and '. Also, Print("hi") with a capital P is an error: Python is case-sensitive.

Exam trap. print("a", "b") prints a b (space added). print("a" "b") without a comma prints ab. Know that # starts a comment and that comments never change what a script does.

The mystery line

A script had a line vlan = 40 that nobody could explain. The author had left. The next engineer added a comment after asking around: vlan = 40 # guest Wi-Fi VLAN per site design. Two years later an auditor read that comment and understood the script without asking anyone.

Lesson: comments explain why; the code already shows what.

"What does print do and how do you add notes to a script?"

print() writes values to the screen, with a space between comma-separated items and a newline at the end by default. Notes are added as comments that start with #; Python ignores them. Comments should explain intent, not repeat the code.

Key takeaways

  • print() displays values; commas add a space; sep and end change the layout.
  • Text needs matching quotes; numbers do not.
  • A comment starts with # and is ignored; use it for why, and to switch a line off.
  • A missing closing quote is a SyntaxError reported before anything runs.
03

Variables: named boxes for values

Imagine you are configuring ten ports for VLAN 10 and your manager changes the VLAN to 20. If you typed "10" in ten places you must find and change all ten. If you typed it once, in a labelled place, you change one thing. A variable is that labelled place: a name that points to a value. Variables are how scripts remember things.

hostname"R1" vlan10 site"PUNE"

Three variables: the name is the label on the box, the value is what is inside.

Creating a variable

You create a variable with a single equals sign. Read = as "gets" or "is set to", not as "equals": the name on the left receives the value on the right.

hostname = "R1"
vlan = 10
site = "PUNE"
print(hostname, vlan, site)
AUTO> python3 v1.py
R1 10 PUNE

You can change what is in a box at any time by assigning again. Python always works out the right side first, then stores it. So vlan = vlan + 1 means "take the value in vlan, add 1, put the answer back in vlan".

vlan = 10
print("before:", vlan)
vlan = 20
print("after:", vlan)
vlan = vlan + 1
print("plus one:", vlan)
backup = vlan
vlan = 99
print(vlan, backup)
AUTO> python3 v2.py
before: 10
after: 20
plus one: 21
99 21

The last two lines show that backup = vlan copies the value at that moment. Changing vlan later does not change backup.

Rules for names

  • Use letters, digits and underscores. The name cannot start with a digit.
  • Names are case-sensitive: hostname and Hostname are different boxes.
  • No spaces. Programmers write mgmt_ip (words joined by underscores, called snake_case).
  • Choose meaningful names: mgmt_ip beats x. Names written in CAPITALS, such as ROUTERS, are a habit for settings that you do not intend to change while the script runs.

Two mistakes that beginners meet within the first hour. A name starting with a digit, and a change of case:

1ip = "10.99.0.1"
AUTO> python3 v3.py
  File "v3.py", line 1
    1ip = "10.99.0.1"
    ^
SyntaxError: invalid decimal literal
hostname = "R1"
print(Hostname)
AUTO> python3 v4.py
Traceback (most recent call last):
  File "v4.py", line 2, in <module>
    print(Hostname)
NameError: name 'Hostname' is not defined. Did you mean: 'hostname'?

NameError means Python was asked for a name that does not exist yet. Notice that Python even suggests the name you probably meant: Did you mean: 'hostname'?.

Worked example. In the Lab 1 script, interface = "GigabitEthernet0/1" and vlan = 10 sit at the top. To build the config for port Gi0/2 in VLAN 20 you edit only those two lines. The rest of the script, which uses the names, does not change.

Common mistake. Writing vlan == 10 when you mean to store a value. One equals sign stores; two equals signs compare (you will meet them in chapter 7). Also, a variable must exist before you use it: print it before the line that creates it and you get a NameError.

Exam trap. Be ready to trace a short sequence of assignments by hand. For a = 5, b = a, a = 7, the value of b is still 5.

One variable, forty ports

A script printed a config for 40 ports using a variable vlan. When the design changed from VLAN 10 to VLAN 30, the engineer edited one line at the top and re-ran the script. All 40 port configs were updated and reviewed in minutes, with no search-and-replace risk.

Lesson: put every value that may change in a variable near the top.

"What is a variable in Python?"

A variable is a name bound to a value, created by assignment with =. It lets a script store, reuse and change values. Names are case-sensitive, cannot start with a digit and should be meaningful, for example mgmt_ip. Assigning again replaces what the name refers to.

Key takeaways

  • A variable is a name pointing to a value; create it with =.
  • Assigning again replaces the value; vlan = vlan + 1 adds one.
  • Names are case-sensitive, have no spaces and cannot start with a digit.
  • NameError means the name does not exist yet or is misspelt.
04

Strings and integers: text versus numbers

A phone book lists "Asha 9876" and a calculator adds 9876 + 1. Both show digits, but you would never add one to a phone number. Python draws the same line. Every value has a type, and the type decides what you are allowed to do with it. Two types do most of the work in network scripts: str (text) and int (whole numbers).

TypeMeaningExamples
strText, always in quotes"R1", "10.99.0.1", "Gi0/1"
intWhole number, no quotes10, 4094, -1
floatNumber with a decimal point2.5, 99.9
boolYes or noTrue, False

The built-in type() tells you the type of anything. Notice that an IP address in quotes is text, not a number, and that "10" in quotes is also text:

print(type("10.99.0.1"))
print(type("10"))
print(type(10))
print(type(2.5))
print(type(True))
AUTO> python3 s1.py
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

What + does depends on the type

With numbers, + adds. With strings, + joins them end to end. The * sign repeats a string, which is perfect for drawing a line in a report.

print(10 + 5)
print("10" + "5")
print("Gi" + "0/1")
print("-" * 20)
print("ab" * 3)
AUTO> python3 s2.py
15
105
Gi0/1
--------------------
ababab

"10" + "5" gave 105 (text joined), not 15. That is the whole difference between str and int in one line.

Converting between types

Output from routers always arrives as text. To do maths on a number that arrived as text, convert it with int(). To put a number inside text, convert it with str().

vlan_text = "10"
print(int(vlan_text) + 5)
vlan = 10
print("VLAN " + str(vlan))
print(float("2.5") + 1)
AUTO> python3 s3.py
15
VLAN 10
3.5

Mixing the two types without converting is an error. Python refuses to guess:

vlan = 10
print("VLAN " + vlan)
AUTO> python3 s4.py
Traceback (most recent call last):
  File "s4.py", line 2, in <module>
    print("VLAN " + vlan)
TypeError: can only concatenate str (not "int") to str

TypeError: can only concatenate str (not "int") to str says: you tried to join text with a number. Fix it with str(vlan), or, even better, with an f-string (chapter 6).

Looking inside a string

A string is a row of characters. len() counts them. A number in square brackets picks one character, counting from 0; a negative number counts from the end; two numbers with a colon take a slice (the end position is not included).

name = "PUN-CORE-01"
print(len(name))
print(name[0])
print(name[-1])
print(name[0:3])
AUTO> python3 s5.py
11
P
1
PUN

Worked example. A hostname is PUN-CORE-01. The first three characters, name[0:3], give the city code PUN. Scripts often use a name pattern like this to decide which site a device belongs to.

Common mistake. Believing that "10" and 10 are the same. They print the same but behave differently: "10" + "5" is 105, while 10 + 5 is 15. Values read from show output or files are text until you convert them.

Exam trap. Typical question: "What does "5" * 3 print?" Answer 555 (a string repeated). And "5 * 3" is 15. Know that int("abc") raises a ValueError.

Adding up port counts

A script read "24" and "48" from two outputs and printed 2448 as the total number of ports. The engineer had joined two strings. After converting each with int() the total became 72. Values that look like numbers are still text until you convert them.

Lesson: convert text to int before doing maths on it.

"What is the difference between "10" and 10 in Python?"

"10" is a string (text); 10 is an integer. Strings are joined with + and repeated with *; integers are added and multiplied. Convert with int() and str(). Mixing them with + raises a TypeError.

Key takeaways

  • str is text in quotes; int is a whole number; type() tells you which.
  • + adds numbers but joins strings; * repeats a string.
  • Use int() and str() to convert; mixing without converting is a TypeError.
  • len(), [0], [-1] and [0:3] look inside a string; counting starts at 0.
05

String methods: cleaning and checking text

Text from the real world is messy. A site name arrives as " pune " with extra spaces and small letters, an interface as "GigabitEthernet0/1" when a report wants "Gi0/1". Python strings come with built-in actions called methods for exactly these jobs. A method is called with a dot after the value: value.method().

Cleaning methods

site = "  pune  "
print("[" + site + "]")
print("[" + site.strip() + "]")
print(site.strip().upper())
print("R1-CORE".lower())
print("pune".title())
AUTO> python3 m1.py
[  pune  ]
[pune]
PUNE
r1-core
Pune
  • strip() removes spaces (and new lines) from both ends.
  • upper(), lower(), title() change the case.
  • You can chain methods: site.strip().upper() strips first, then capitalises.

Important: a method never changes the original. It returns a new string. If you want to keep the result, store it in a variable:

site = "  pune  "
site.strip()
print("[" + site + "]")
site = site.strip()
print("[" + site + "]")
AUTO> python3 m2.py
[  pune  ]
[pune]

The first strip() threw its answer away, so site still has spaces. The assignment site = site.strip() keeps it.

Replacing and checking

intf = "GigabitEthernet0/1"
print(intf.replace("GigabitEthernet", "Gi"))
print(intf.startswith("Gig"))
print(intf.startswith("Fast"))
print("0/1" in intf)
print(intf.endswith("1"))
print("a-b-c".count("-"))
AUTO> python3 m3.py
Gi0/1
True
False
True
True
2

replace(old, new) swaps every copy of old for new. startswith, endswith and the word in answer yes/no questions with True or False. They are the building blocks of the decisions you will write in the next module.

Cutting and joining: split and join

split() cuts a string into a list of pieces. With no argument it cuts at any run of spaces; with an argument it cuts at that character. join() does the opposite: the separator comes first, then the list.

line = "Gi0/0 10.99.0.1 up up"
parts = line.split()
print(parts)
print(parts[1])
print("10.99.0.1".split("."))
print("PUN-CORE-01".split("-")[0])
print(",".join(["Gi0/1", "Gi0/2", "Gi0/3"]))
AUTO> python3 m4.py
['Gi0/0', '10.99.0.1', 'up', 'up']
10.99.0.1
['10', '99', '0', '1']
PUN
Gi0/1,Gi0/2,Gi0/3

The line above looks like a row from show ip interface brief. After split() each column is one item of the list, and parts[1] is the IP address. This is exactly how scripts read device output.

MethodResult for " Gi0/1 "
strip()"Gi0/1"
strip().upper()"GI0/1"
strip().replace("Gi", "Fa")"Fa0/1"
split("/")[' Gi0', '1 ']

Common mistake. Writing site.strip without brackets. That gives the method itself, not the cleaned text. Always put () after a method name. And remember that methods return new strings: store the result.

Exam trap. Know the return values: "a,b".split(",") is a list ['a', 'b']; "a" in "cat" is True; "cat".replace("c", "b") is "bat". strip() removes only the ends, not spaces in the middle.

Reports that did not match

Two reports listed the same site as "Pune", "pune " and "PUNE". A comparison script counted three different sites. Adding .strip().upper() to every site name before comparing made the data agree and the count dropped to one.

Lesson: clean and normalise text before you compare it.

"How would you turn a line of show output into separate fields?"

Use split(): it cuts the line at whitespace and returns a list, so each column becomes an item you can pick by index. For other separators pass the character, for example split(","). For complex output you would later use a parsing library, but split is the foundation.

Key takeaways

  • A method is an action called with a dot: value.method().
  • strip, upper, lower, replace clean text; they return a new string.
  • startswith, endswith and in give True or False.
  • split cuts a string into a list; join glues a list into a string.
06

f-strings: the easiest way to build config lines

You can already join text with + and convert numbers with str(). It works, but it is clumsy: "interface " + name + " vlan " + str(vlan) is easy to mistype. Python has a much nicer tool, the f-string (formatted string literal). It is a template with blanks. Put the letter f directly before the opening quote, and write {name} wherever you want a variable's value to appear.

interface = "GigabitEthernet0/2"
vlan = 20
site = "PUNE"
print(f"interface {interface}")
print(f" description Link to {site} - VLAN {vlan}")
print(f" switchport access vlan {vlan}")
print(f" ip address 10.1.{vlan}.1 255.255.255.0")
AUTO> python3 f1.py
interface GigabitEthernet0/2
 description Link to PUNE - VLAN 20
 switchport access vlan 20
 ip address 10.1.20.1 255.255.255.0

The output is configuration that you can paste straight into a switch. Three details matter:

  • The f must be directly before the quote, with no space.
  • Numbers need no str(); the f-string converts them for you.
  • Inside the braces you may put a calculation or a method: {site.lower()}, {vlan + 100}.
site = "PUNE"
vlan = 20
print(f"{site.lower()}-sw-{vlan + 100}")
AUTO> python3 f2.py
pune-sw-120

Formatting numbers

After the value you may add a colon and a format. {n:03d} pads a whole number with zeros to three digits; {x:.2f} shows two decimals; {text:>8} right-aligns text in 8 characters. Useful for neat, equal-width names like SW-007.

n = 7
print(f"SW-{n:03d}")
print(f"{3.14159:.2f}")
print(f"[{'Gi0/1':>8}]")
AUTO> python3 f3.py
SW-007
3.14
[   Gi0/1]

Two traps: the missing f and literal braces

Forget the f and Python prints the braces exactly as typed. If you want real braces in the output, double them:

vlan = 10
print("vlan {vlan}")
print(f"vlan {vlan}")
print(f"{{vlan}} is {vlan}")
AUTO> python3 f4.py
vlan {vlan}
vlan 10
{vlan} is 10

Lab 1 walk-through

In the lab you run hello_router.py, change two variables and add one line. Here are the lines with their numbers, so you know which line to edit:

AUTO> nl hello_router.py
     1  # hello_router.py - build interface config lines with Python
     2  # A VARIABLE is a named box that stores a value.
     3  interface = "GigabitEthernet0/1"   # a string (text): always inside quotes
     4  vlan = 10                          # an integer (whole number): no quotes
     5  site = "  pune  "                  # messy text with extra spaces
     6  
     7  # print() shows something on the screen
     8  print("Building config...")
     9  
    10  # .strip() removes spaces at both ends, .upper() makes CAPITAL letters
    11  clean_site = site.strip().upper()
    12  
    13  # f-string: put f before the quote, then {name} is replaced by its value
    14  print(f"interface {interface}")
    15  print(f" description Link to {clean_site} - VLAN {vlan}")
    16  print(" switchport mode access")
    17  print(f" switchport access vlan {vlan}")

First run with the original values, then change the port and the VLAN (lines 3 and 4 only), and run again:

AUTO> python3 hello_router.py
Building config...
interface GigabitEthernet0/1
 description Link to PUNE - VLAN 10
 switchport mode access
 switchport access vlan 10
AUTO> edit hello_router.py 3 interface = "GigabitEthernet0/2"
AUTO> sed -i 's/vlan = 10/vlan = 20/' hello_router.py
AUTO> python3 hello_router.py
Building config...
interface GigabitEthernet0/2
 description Link to PUNE - VLAN 20
 switchport mode access
 switchport access vlan 20

Finally add one more line at the end (the file has 17 lines, so insert as line 18) that prints the short interface name with replace():

AUTO> insert hello_router.py 18 print(interface.replace("GigabitEthernet", "Gi"))
AUTO> python3 hello_router.py
Building config...
interface GigabitEthernet0/2
 description Link to PUNE - VLAN 20
 switchport mode access
 switchport access vlan 20
Gi0/2

The site in the description is PUNE: the variable held " pune ", and .strip().upper() in line 11 cleaned it before the f-string used it. Line 4 holds vlan = 20 without quotes, so it is an int.

Common mistake. Using single quotes inside a single-quoted f-string, for example f'{info['ip']}', or forgetting a closing brace. Pick the other quote type for what is inside the braces: f"{info['ip']}".

Exam trap. An f-string needs the f prefix to substitute values. Know what f"{{x}}" prints (the text {x}) and that format specs such as :03d or :.2f follow a colon inside the braces.

Generating 24 descriptions

An engineer needed descriptions for 24 uplinks named by floor and port number. Instead of typing them she wrote one f-string with a floor variable and a port variable, and the script printed all 24 lines. Her peer reviewed one line of template instead of 24 lines of text.

Lesson: reviewing one template is safer than reviewing many copies.

"What is an f-string and why use it?"

An f-string is a string with an f prefix where expressions in curly braces are evaluated and inserted. It is more readable than concatenation, converts numbers automatically and supports format specifications. It is ideal for building configuration lines, log messages and URLs from variables.

Key takeaways

  • Put f before the quote and {name} where a value belongs.
  • Numbers are converted for you; braces can hold calculations and methods.
  • Without the f, braces print literally; double them to print real braces.
  • Format specs follow a colon: {n:03d}, {x:.2f}.
07

Numbers, maths and booleans

Networking is full of numbers: VLAN IDs, hop counts, uptime days, a /24 holding 254 hosts. Python can calculate all of them. It can also answer yes/no questions such as "is this VLAN in range?" The yes/no answers are called booleans. They are the doorway to decisions, which you will write in the next module.

The arithmetic operators

OperatorMeaningExample
+ - *add, subtract, multiply10 * 3 is 30
/divide (always gives a float)7 / 2 is 3.5
//whole-number divide7 // 2 is 3
%remainder7 % 2 is 1
**power2 ** 8 is 256
print(10 * 3)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(2 ** 8)
print(2 ** 8 - 2)
print(int(7 / 2))
print(round(7 / 3, 2))
AUTO> python3 n1.py
30
3.5
3
1
256
254
3
2.33

2 ** 8 - 2 is 254: a /24 has 8 host bits, so 256 addresses, minus the network and broadcast addresses. Python follows normal maths order: power first, then multiply and divide, then add and subtract; use brackets to be sure.

A small surprise: computers store decimals approximately, so very small errors can appear.

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(type(3 / 1))
print(3 + 2.5)
AUTO> python3 n2.py
0.30000000000000004
0.3
<class 'float'>
5.5

Booleans: True and False

A boolean has only two possible values, True and False (capital first letter, no quotes). You get them by comparing. A comparison asks a question and returns a boolean.

ComparisonAsks
a == bEqual? (two equals signs)
a != bNot equal?
a < b a > bSmaller or bigger?
a <= b a >= bSmaller or equal, bigger or equal?
x in textIs x inside?
vlan = 10
uptime_days = 42
print(vlan == 10)
print(vlan != 10)
print(uptime_days > 30)
print(1 <= vlan <= 4094)
print("Gi" in "GigabitEthernet0/1")
AUTO> python3 n3.py
True
False
True
True
True

Booleans can be combined with and, or and not. and needs both sides true, or needs at least one, not flips the answer.

is_core = True
is_old = False
print(is_core and is_old)
print(is_core or is_old)
print(not is_old)
print(3 > 2 and 2 > 5)
print(bool(""), bool("R1"), bool(0), bool(5))
AUTO> python3 n4.py
False
True
True
False
False True False True

The last line shows "truthiness": an empty string and zero count as False; any non-empty text and any non-zero number count as True. Scripts use this to test "did the router return anything?".

Worked example. A VLAN ID is valid when 1 <= vlan <= 4094. For 10 the answer is True; for 5000 it is False. In the next module the script will print an error message only when this comparison is False.

Common mistake. Writing = when you mean ==. vlan = 10 stores; vlan == 10 asks. Also, "true" in quotes is text, not the boolean True, and / always returns a float: 10 / 2 is 5.0, not 5.

Exam trap. Know // and %: 17 // 5 is 3 and 17 % 5 is 2. Remember that the result of a comparison is a boolean, and that "administratively down" == "down" is False because strings must match exactly.

The VLAN that was never valid

A bulk-config script accepted VLAN 5000 from a spreadsheet and the switch rejected it, leaving a half-built config. After the team added the range comparison 1 <= vlan <= 4094 as a check, the script stopped before sending anything and printed which row had the problem.

Lesson: validate input with a comparison before you send anything to a device.

"What is a boolean and where do you get one?"

A boolean is a value that is either True or False. It is the result of a comparison such as ==, > or in, and can be combined with and, or and not. Conditions in if statements are booleans.

Key takeaways

  • Operators: + - * / // % ** ; / always gives a float.
  • A comparison (==, !=, <, >, in) returns True or False.
  • and, or, not combine booleans; empty text and zero count as False.
  • One = stores a value; two == compares.
08

Fixing errors: the broken report

Professionals do not write error-free code. They read errors well. Python reads the whole file first; if the text is not valid Python at all, it stops with a SyntaxError before anything runs. If the file is valid, Python runs line by line and stops at the first line that fails, printing a traceback. In both cases, read the last line first and then the line number. The loop is: run, read, fix one thing, run again.

ErrorMeansTypical fix
SyntaxErrorText is not valid PythonClose the quote or bracket, add the colon
NameErrorUnknown nameFix the spelling or create the variable first
TypeErrorWrong type for the operationConvert, or use an f-string

Lab 2: the report that never ran

A fresher wrote report.py to print a daily health report. It has three classic beginner bugs. Here is the file with line numbers:

AUTO> nl report.py
     1  # report.py - print a short health report for one router
     2  hostname = "BLR-EDGE-01"
     3  uptime_days = 42          # int (a number)
     4  interfaces_up = 3         # int (a number)
     5  
     6  print("=== Daily router report ===)
     7  print("Router: " + hostnme)
     8  print("Uptime in days: " + uptime_days)
     9  print(f"Interfaces up: {interfaces_up}")
    10  print("=== End of report ===")

Bug 1: SyntaxError

AUTO> python3 report.py
  File "report.py", line 6
    print("=== Daily router report ===)
          ^
SyntaxError: unterminated string literal (detected at line 6)

Python names the line (6) and the problem: a string with no closing quote. Notice that nothing printed at all, even though lines 1 to 5 look fine: the whole file is checked first. Fix line 6:

AUTO> edit report.py 6 print("=== Daily router report ===")

Bug 2: NameError

AUTO> python3 report.py
=== Daily router report ===
Traceback (most recent call last):
  File "report.py", line 7, in <module>
    print("Router: " + hostnme)
NameError: name 'hostnme' is not defined. Did you mean: 'hostname'?

Now the file is valid Python, so it starts running and prints the first line. It stops at line 7 because hostnme is a misspelling of hostname, and Python suggests the fix. Correct the spelling:

AUTO> sed -i 's/hostnme/hostname/' report.py

Bug 3: TypeError

AUTO> python3 report.py
=== Daily router report ===
Router: BLR-EDGE-01
Traceback (most recent call last):
  File "report.py", line 8, in <module>
    print("Uptime in days: " + uptime_days)
TypeError: can only concatenate str (not "int") to str

Line 8 tries to join the text "Uptime in days: " with the integer uptime_days. Use an f-string, as in chapter 6:

AUTO> edit report.py 8 print(f"Uptime in days: {uptime_days}")
AUTO> python3 report.py
=== Daily router report ===
Router: BLR-EDGE-01
Uptime in days: 42
Interfaces up: 3
=== End of report ===

The report is complete: the router name, 42 days of uptime and 3 interfaces up. Three errors, three small fixes, each found by reading one message.

Common mistake. Fixing several things at once, then not knowing which change helped. Fix one error, run again, read the next message. Also do not ignore the line number: it is usually where Python noticed the problem, and the real cause is on that line or just above it.

Exam trap. Match the message to the cause: "unterminated string literal" is a missing quote, "is not defined" is a NameError (spelling or order), "can only concatenate str (not int)" is a TypeError from joining text with a number.

The Friday-afternoon report

A junior engineer had to send a report in an hour. The script failed three times in a row. Instead of panicking he read each last line, fixed the one thing it named, and ran again. Three minutes later the report printed correctly. His senior later said he made the same three errors in his first week.

Lesson: errors are information; read the last line and fix one thing at a time.

"How do you debug a Python script that fails?"

Read the last line of the message for the error type and text, go to the line number it gives, check the usual causes for that error type (quote or bracket for SyntaxError, spelling for NameError, converting types for TypeError), fix one thing, and re-run. If needed, add temporary print() calls to see variable values.

Key takeaways

  • SyntaxError appears before anything runs; NameError and TypeError appear when the failing line runs.
  • Read the last line, then the line number.
  • Fix one error at a time and re-run.
  • Python often suggests the right name with Did you mean.
09

Summary and exam checklist

You can now display text, store values, tell text from numbers, clean strings, build configuration with f-strings, compare values and read the three most common errors. These are the foundation of every automation script. This page is your revision sheet.

Can-do checklist

  • Print text, numbers and several values with print().
  • Write a comment and use it to switch a line off.
  • Create and change variables; follow the naming rules.
  • Say whether a value is str, int, float or bool, and convert with int() and str().
  • Clean text with strip, upper, lower and replace; cut it with split.
  • Build config lines with an f-string, including formats such as :03d.
  • Use arithmetic and comparisons, and predict True or False.
  • Fix a SyntaxError, a NameError and a TypeError from the message.

Mini glossary

Variable
A name bound to a value.
str / int / float / bool
Text / whole number / decimal / True-False.
Method
An action on a value: value.method().
f-string
A string starting with f whose braces are filled with values.
Comment
A note after #, ignored by Python.
Boolean
True or False, the result of a comparison.
Traceback
The report Python prints when a script fails.
Concatenate
Join two strings end to end.

Quick reference

IdeaExampleResult
Show textprint("R1", 10)R1 10
Variablevlan = 10stores 10
Typetype("10")<class 'str'>
Convertint("10") + 515
Clean" pune ".strip().upper()PUNE
Cut"a b".split()['a', 'b']
f-stringf"vlan {vlan}"vlan 10
Compare10 == 10True

Most tested facts

  • Quotes make text: "10" + "5" is 105; 10 + 5 is 15.
  • String methods return a new string; they do not change the original.
  • Counting starts at 0; [0:3] excludes position 3.
  • Without the f, an f-string is plain text and the braces print as typed.
  • = stores, == compares; / always returns a float.
  • SyntaxError appears before the script runs; NameError means an unknown name; TypeError means a wrong type.

Next: "Python 2" teaches lists, dictionaries, for loops and if/else decisions, so your scripts can handle many devices and choose what to do.

Ready for devices

A trainee finished these chapters and wrote a ten-line script that built the configuration for a new access port from five variables. The senior reviewed the five variables, not the ten lines of output, and approved it. A week later the trainee extended it to loop over twenty ports, using lists from the next module.

Lesson: variables plus f-strings are the base on which loops and lists build.

"Give an example of Python that a network engineer might write in the first week."

A small script that stores an interface name, a VLAN and a site in variables and prints the matching configuration lines with an f-string. It shows you understand variables, strings and formatting, and it is genuinely useful because it removes copy-paste errors.

Key takeaways

  • Variables, types, string methods and f-strings build config text.
  • Comparisons give booleans, the basis of decisions.
  • Read errors from the last line and fix one thing at a time.
  • Next: lists, dictionaries, loops and if/else in Python 2.
๐ŸŽ“ For educational purposes only โ€” all devices are simulationsTerms of UsePrivacy Policyยฉ 2026 Network Kings
CONFIG by Network Kings โ€” an educational IT simulation platform for learning purposes only. It is not Cisco IOS, Junos, FortiOS or PAN-OS and contains no Cisco, Juniper, Fortinet or Palo Alto Networks software. Cisco, IOS, CCNA, CCNP, Juniper, JNCIA, JNCIS, JNCIP, Fortinet, FortiGate, FortiOS, NSE, Palo Alto Networks, PAN-OS and PCNSE are trademarks of their respective owners. Network Kings is not affiliated with or endorsed by Cisco Systems, Inc., Juniper Networks, Inc., Fortinet, Inc. or Palo Alto Networks, Inc.