Exam objective 3.1 for the 200-901 DevNet Associate asks you to describe Python data types, conditionals, loops, functions, and common libraries. These are the fundamental building blocks that let you write scripts to talk to network devices instead of typing commands one by one. Mastering them means you can automate repetitive network tasks, save hours of work, and pass the exam.
Jump to a section
A simple way to picture Python Programming Fundamentals for Network Automation
The head chef at a busy restaurant does not memorise every single recipe for every single dish. Instead, the chef keeps a master recipe book organised into sections: a list of ingredients (data types), instructions to decide what to do based on what is in the fridge (conditionals), a method to repeat a step like peeling ten potatoes (loops), and a set of standard procedures like making a base sauce (functions).
When a new delivery of vegetables arrives, the chef uses the section on ingredients to check that the tomatoes are actually tomatoes (a string, not a number) and that the weight is a number (an integer). The chef then uses a conditional to decide: if the tomatoes are ripe, make a salad; otherwise, make a soup. The chef uses a loop to peel each of the ten potatoes one by one. Finally, the chef uses a function for the base sauce so that any time a recipe needs it, the chef just follows that standard procedure rather than writing out the steps again.
For the network automation beginner, Python is exactly that master recipe book. Data types are the ingredients. Conditionals are the if-this-then-that decisions. Loops are the repetitive tasks like checking every router. Functions are the reusable procedures for tasks like backing up a configuration. Just as the chef never has to reinvent the base sauce every time, the network engineer never has to rewrite the same code for a common task.
Python is a programming language that lets you give instructions to a computer. In network automation, you use Python to tell a switch or router what to do. To do that, you need to understand five core concepts: data types, conditionals, loops, functions, and common libraries.
Data types are the categories of information Python can handle. The most common ones are: - String: a sequence of characters, like a word or sentence. You write it in quotes, for example "Hello" or "192.168.1.1". A string is just text. - Integer: a whole number, like 10, 0, or -5. No decimal points. - Float: a number with a decimal point, like 3.14 or 2.0. - Boolean: either True or False. It is the result of a yes/no question. - List: an ordered collection of items, written in square brackets, like [1, 2, 3] or ["router1", "router2"]. You can add, remove, or change items. - Dictionary: a collection of key-value pairs, written in curly braces, like {"name": "router1", "ip": "10.0.0.1"}. Each key is like a label for a value.
Why do data types matter? When you write a script to read a device's configuration, the device might return a string of text. If you try to do arithmetic on that string, Python will give an error because you cannot add a string to an integer. You have to convert it first. For example, if you receive "10" as a string, you use int("10") to turn it into the integer 10 before doing maths.
Conditionals let your code make decisions. The basic structure is an if statement:
- if condition: do something - elif other_condition: do something else - else: do this if nothing matched
For example, you might check the status of a network interface. If the interface is "up", continue. If it is "down", send an alert. This replaces a human who would look at a status and decide what to do.
Loops let you repeat actions without writing the same line over and over. The most common loop in Python is the for loop:
- for item in list_of_items: do something with item
Imagine you have a list of 100 routers. Without a loop, you would have to write 100 separate commands. With a loop, you write one block of code that runs for each router. Python will go through the list, take the first router, do the task, then take the second, and so on until it finishes.
Functions are reusable blocks of code. You define a function once and call it by name whenever you need it. For example:
- def backup_config(device_ip): # code to back up configuration
Then you can call backup_config("10.0.0.1") and it runs the backup code for that device. Functions make your code shorter, easier to read, and easier to fix because you only change the code in one place.
Common libraries are pre-written code packages that other people have created. Instead of writing everything from scratch, you import a library and use its ready-made tools. For network automation, the most important libraries are: - netmiko: connects to network devices (Cisco, Juniper, etc.) over SSH and runs commands. - napalm: provides a standard way to get configuration and state information from different devices. - json: lets you work with JSON data, which is a common format for API responses. - requests: sends HTTP requests to web APIs (like a REST API on a controller).
To use a library, you first install it (usually with pip install library_name) and then import it at the top of your script like:
import netmiko
from netmiko import ConnectHandler
Then you can create a connection to a device and send commands.
All these pieces fit together. You use data types to hold information. You use conditionals to make decisions based on that information. You use loops to perform the same task on many items. You use functions to organise your code into logical blocks. And you use libraries to avoid reinventing the wheel. This is the foundation of writing Python scripts that automate network tasks.
Define your data with variables and data types
Choose the right container for your information. For a single device IP, use a string. For a list of all device IPs, use a list. For device properties like name and IP, use a dictionary. Making the right choice early prevents type errors later.
Write a conditional to decide what to do
Use 'if' statements to check conditions like device reachability or configuration status. For example, 'if ping_result == "success":' lets you skip devices that are offline. This replaces human decision-making with automatic logic.
Create a loop to repeat the task for every device
Use a 'for' loop to iterate over your list of devices. Inside the loop, place the code that connects, retrieves data, or checks status. This single loop can handle tens, hundreds, or thousands of devices without extra code.
Encapsulate reusable logic in a function
Define a function for common actions like backing up a device or sending an alert. This makes your script modular. If you need to change the backup method, you only edit the function, not every place the backup is called.
Import and use a common library for specialised tasks
Instead of writing your own SSH client, import netmiko. Instead of parsing JSON manually, import json. Libraries save time and use well-tested code. You install them once with 'pip' and then import at the top of your script.
Test and debug with print statements and error handling
Use print() to check variable values at different stages. Add try-except blocks to catch errors gracefully. For example, wrap the connection code in a try block and catch exceptions like AuthenticationException to log failures without crashing the script.
Consider Taylor, a junior network engineer at a mid-sized company that manages 50 Cisco switches across three offices. Every Monday morning, Taylor connects to each switch via a terminal session, types show running-config, copies the output, and pastes it into a text file for backup. This takes three hours and is boring, error-prone work. Taylor wants to automate it.
Taylor writes a Python script using the netmiko library. First, Taylor defines a list of all device IP addresses as a Python list data type:
devices = ["10.0.1.1", "10.0.1.2", "10.0.2.1", ...]
Next, Taylor writes a function called backup_device that takes one device IP as input. Inside the function, Taylor uses a conditional: if the device is reachable (tested with ping), proceed; else, log an error and skip it. Then Taylor connects to the device, runs the show command, and saves the output to a file named with the device IP and date.
Taylor then uses a for loop to call the backup_device function for every IP in the list:
- for ip in devices: backup_device(ip)
That three-hour Monday morning task now runs in under two minutes. Taylor also adds a dictionary data type to store configuration metadata: the device name, IP, last backup time, and status. When a device fails to connect, the dictionary entry for that device gets updated with status: "backup_failed". Taylor can then look at the dictionary to see which devices need manual attention.
Later, Taylor adds more conditionals. If a device's configuration has changed since the last backup (checked by comparing file hashes), Taylor wants to know about it. So the script now includes an if statement that compares the hash of the new backup with the old one. If they are different, the script sends an email notification using the smtplib library.
Taylor also imports the json library to read an inventory file. The inventory is a JSON file that lists all devices with their IPs, credentials, and device types. Taylor's script reads this file, converts it into a Python dictionary, and uses the information to connect to each device. This means Taylor does not have to hard-code credentials in the script, which is safer.
What was once a tedious manual task is now a fully automated Python script. Taylor uses functions to keep the code organised, data types to store and move information, conditionals to make smart decisions, loops to handle all devices, and common libraries to do the heavy lifting. This is exactly the kind of automation the DevNet Associate exam wants you to understand and build.
The 200-901 exam tests your understanding of Python fundamentals in the context of network automation. You will not be asked to write long scripts from scratch. Instead, the exam presents multiple-choice questions that ask you to read a short code snippet and identify the output, find the bug, or choose the correct definition. Here is exactly what you need to know.
Data types are a frequent topic. The exam tests whether you can identify the type of a variable. For example, they might show:
x = "10"
And ask: what is the type of x? The correct answer is string (str). If they show:
y = [1, 2, 3]
The type is list. They also test how to convert between types: int() turns a string into an integer, str() turns an integer into a string. A common trap is trying to concatenate a string and an integer. For example:
print("The number is " + 5)
This causes a TypeError because you cannot add a string and an integer. The fix is str(5).
Conditionals appear in questions where you have to predict the output of an if-elif-else block. They will include comparison operators like == (equals), != (not equals), >, <, >=, <=, and logical operators like and, or, not. A common trap: using a single equals sign (=) instead of double (==) inside an if condition. A single equals is assignment, not comparison. The exam expects you to catch that error.
Loops are tested by asking what a for loop will print. They might give you a list and a loop, and ask for the final value of a variable after the loop ends. Another trap: forgetting to initialise a counter before the loop. For example:
- total = 0 - for i in [1, 2, 3]: total = total + i - print(total) # prints 6
If total is not initialised, the code will error. They also test the range() function: range(5) gives 0 to 4. range(1, 5) gives 1 to 4.
Functions are tested by asking what a function returns, especially when the function has a return statement. If there is no return, the function returns None. A trap: confusing print() with return. A function that prints a value does not return it. You cannot assign the output of print() to a variable and use it later. Only return gives back a value.
Common libraries are tested at a high level. You need to know what each library is used for: - netmiko: SSH connections to network devices. - napalm: retrieving and comparing network state. - json: parsing JSON data. - requests: making HTTP requests to APIs. - os: interacting with the operating system (file paths, environment variables).
The exam will not ask you to write a full script using these libraries, but they might give you a snippet that imports a library and ask which library was used, or what a specific function from that library does.
Finally, the exam loves questions about indentation. Python uses indentation (spaces or tabs) to define blocks of code inside if statements, loops, and functions. If the indentation is wrong, Python throws an IndentationError. A typical question shows a code block with mixed tabs and spaces, or missing indentation, and asks what error occurs. The correct answer is always an indentation error.
To prepare, practise reading code snippets line by line. Do not just memorise definitions. Work through the output in your head or on paper. The exam is designed to test your ability to trace through code, not your ability to write it from memory.
Python has five core data types you must know: string, integer, float, boolean, list, and dictionary.
Conditionals ('if', 'elif', 'else') let your code make decisions based on comparisons and logical tests.
A 'for' loop iterates over a sequence like a list; a 'while' loop runs as long as a condition is true.
Functions are defined with 'def' and must use 'return' to send a value back; otherwise they return 'None'.
Common network automation libraries include netmiko (SSH to devices), napalm (state retrieval), json (data parsing), and requests (HTTP APIs).
Indentation errors are a frequent exam trap: Python requires consistent indentation to define code blocks within conditionals, loops, and functions.
You must use double equals '==' for comparison inside an 'if' statement; a single '=' is for assignment and will cause a logical error.
The 'range()' function generates a sequence of numbers, starting from 0 by default, and is often used to control how many times a loop runs.
These come up on the exam all the time. Here's how to tell them apart.
List
Ordered: items have a specific index position (0, 1, 2...)
Accessed by index number: my_list[0] gives the first item
Best for sequences where order matters, like a list of device IPs
Dictionary
Unordered: items are stored as key-value pairs (no index)
Accessed by key: my_dict['ip'] gives the value for 'ip'
Best for storing properties or attributes, like a device's name and IP
For Loop
Iterates over a finite sequence (e.g., list, string, range)
Automatically stops after the last item; no risk of infinite loop if sequence is fixed
Best when you know exactly how many times to repeat (e.g., for each router in a list)
While Loop
Runs as long as a boolean condition is True
Requires manual update of the condition variable; easy to create an infinite loop
Best when you do not know the exact number of iterations (e.g., keep trying until connection succeeds)
Print()
Outputs a value to the console; you can see it on screen
Does not send a value back to the caller; the function returns None
Used for debugging or confirming what the code is doing at a point in time
Return
Sends a value back to the part of the code that called the function
The value can be assigned to a variable and used later
Used to provide the result of a function's work to the rest of the program
Integer
Whole number without quotes (e.g., 10, -5, 0)
Supports arithmetic operations like +, -, *, /
Cannot be concatenated with other types directly without conversion
String
Sequence of characters in quotes (e.g., '10', 'Hello')
Does not support arithmetic; + is concatenation for strings
Cannot be used in arithmetic without conversion to integer or float
netmiko
Focuses on sending commands over SSH to network devices
Best for executing 'show' or 'configure' commands directly
Supports many vendors but requires knowing vendor-specific commands
napalm
Focuses on retrieving and comparing network device state (configuration, facts)
Provides a vendor-agnostic API (same method works on Cisco, Juniper, etc.)
Can compare configurations between devices or over time
Mistake
Python variables do not need a declared type, so the type does not matter.
Correct
Python is dynamically typed, meaning you do not declare the type upfront, but the type still matters at runtime. If you try to perform an operation that does not match the type (like adding a string and an integer), Python will raise a TypeError.
Beginners often hear that Python is 'flexible' and assume that means they can treat any variable as any type. They forget that the interpreter still tracks the underlying type and enforces rules when operators are used.
Mistake
A boolean is just a number: True is 1 and False is 0.
Correct
While True and False can behave like 1 and 0 in some contexts (for example, True + True equals 2), they are distinct types. The exam expects you to recognise True and False as booleans, not integers, and understand that they are the only two values of the bool type.
This confusion comes from the fact that Python allows bools to be used in arithmetic, and from other languages where booleans are literally integer values. Beginners see True + 1 = 2 and conclude they are identical.
Mistake
A for loop runs while a condition is True.
Correct
A for loop iterates over a sequence (like a list or string) for a fixed number of times based on the length of that sequence. A while loop runs while a condition is True. Beginners confuse the two because both can repeat actions, but their control mechanisms are different.
The word 'loop' creates a mental association with 'while condition is true', and beginners often do not realise that for loops are finite and predetermined by the collection they iterate over.
Mistake
A function that prints a value can be used directly in an assignment to capture that value.
Correct
A function that prints a value does not return it. Only a function that uses the return keyword can send a value back to the caller. If you write x = print("hello"), x will be None, not the string "hello".
New learners see the output appear on the screen and assume the value is being 'given back'. They do not distinguish between printing (output to screen) and returning (output to the calling code).
Mistake
Variables created inside a function are accessible anywhere after the function runs.
Correct
Variables created inside a function are local to that function. They only exist during the function's execution and are destroyed when the function exits. To make a value available outside, you must return it and assign it to a variable in the outer scope.
Beginners who are used to writing simple sequential scripts think all variables exist everywhere. They do not grasp the concept of scope until they try to access a variable from a function and get a NameError.
Mistake
You must import a library before every single use of a function from that library.
Correct
You import a library once at the top of your script (or once per module). After that, you can use any function from that library throughout the script without re-importing. Re-importing is unnecessary and wasteful.
This comes from a misunderstanding of how Python loads modules. Beginners think each call to a function requires the library to be loaded again, similar to how you might open a file each time you read it.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
A list is an ordered collection of items accessed by an index (0, 1, 2, etc.). A dictionary is an unordered collection of key-value pairs accessed by a key. Use a list when order matters, and a dictionary when you need to look up values by a label.
Python prohibits mixing data types in operations like addition. You must convert the string to an integer using int() or the integer to a string using str() before joining them.
Python uses indentation (spaces or tabs) to define blocks of code under if statements, loops, and functions. An indentation error means the spacing is inconsistent or missing. Fix it by ensuring all lines in the same block have exactly the same indentation.
The 'return' keyword sends a value from the function back to the part of the code that called it. Without 'return', the function returns None. Use 'return' when you need to capture the result of a function in a variable.
Yes. netmiko is a third-party library not included with Python by default. You install it using pip: 'pip install netmiko' in your terminal. After installation, you import it in your script with 'import netmiko'.
A 'for' loop iterates over a fixed sequence (like a list) and stops automatically after the last item. A 'while' loop runs as long as a condition remains True, and you must manually update the condition or it could run forever.
First, import the json library. Then open the file using open(), read its contents, and use json.load() to convert the JSON text into a Python dictionary. For example: import json; with open('file.json') as f: data = json.load(f).
You've finished Python Programming Fundamentals for Network Automation. Continue through the 200-901 study guide to build a complete picture of the exam.
Done with this chapter?