Python Curriculum
On this page
- Why Python For Devops
- Why Python is Popular
- Setting up Your First Script
- Running Python on Any System
- Working with Simple Data
- Using Strings for Text
- Using Numbers for Count and Ports
- Using Booleans for Status Checks
- Working with Collections of Data
- Storing Lists of Items
- Storing Key and Value Pairs
- Making Decisions in Your Code
- Using Simple Checks
- Checking Multiple Conditions
- Repeating Tasks with Loops
- Using For Loops
- Using While Loops
- Grouping Code in Functions
- Creating a Simple Function
- Using Default Arguments
- Handling Errors Gracefully
- Reading and Writing Files
- Writing to a Log File
- Reading from a Log File
- A Real-World Example
- Common Mistakes
- Forgetting to Close Files
- Confusing Strings and Numbers
- Catching All Errors Without Checking
- Summary
Why Python For Devops
When you manage more than one server, doing everything by hand gets messy fast. If you login to five servers to check their disk space, you will spend ten minutes typing the same commands. If you have to do this every day, you will eventually make a mistake. Python lets you write down your steps in a file so the computer can run them for you in less than a second.
This guide covers the basics of Python, starting from why we use it to how you write your first scripts. You will learn how to handle data, make decisions in code, and read files. By the end, you will be able to write scripts that check system health and save you from boring, repetitive work.
Why Python is Popular
You might already know how to write shell scripts using Bash. While Bash is great for running one or two commands, it becomes hard to read when your script grows. Python is much easier to read and write. It runs on Windows, Mac, and Linux, so you do not have to rewrite your scripts when your systems change.
Here is a simple look at how manual work, Bash, and Python compare when you need to automate tasks.
Setting up Your First Script
Before you write any code, you need to know how to run it. Python files end with .py. You write code in a text editor and then run it using your computer's terminal.
Let's start by printing a message to the screen. Create a file named hello.py and write the code below.
To run this code, open your terminal and run this command:
Expected output:
Running Python on Any System
When you write scripts, you need to make sure they run the same way on everyone's computer. Python packages sometimes conflict with each other when you install them globally. You can solve this problem by using virtual environments. A virtual environment is just a private folder where you install libraries for a single project.
Let's create a virtual environment, activate it, and install a package.
Expected output:
Working with Simple Data
To automate systems, you need to store information like server names, IP addresses, and port numbers. Python uses variables to hold this information. You do not need to tell Python what kind of data you are storing; it figures it out automatically.
Using Strings for Text
Strings store words, paths, or IP addresses. You put quotation marks around the text.
Expected output:
Using Numbers for Count and Ports
Integers store whole numbers like port numbers, and floats store decimals like disk space percentages.
Expected output:
Using Booleans for Status Checks
Booleans store either True or False. They help you track whether a check passed or failed.
Expected output:
Working with Collections of Data
Sometimes you need to work with more than one piece of data at a time. For example, you might have a list of five server names or a collection of details about a single database.
Storing Lists of Items
A list keeps items in a specific order. You can add new items, remove items, or read an item using its position number.
Expected output:
Storing Key and Value Pairs
A dictionary stores data in pairs, like a real dictionary. You look up a key to find its value. This is useful for storing settings.
Expected output:
Making Decisions in Your Code
Your scripts need to behave differently depending on the situation. If a disk is full, you want to log a warning. If a service is down, you want to restart it.
Using Simple Checks
You use if statements to compare values. Python looks at the spacing to see which lines belong to the check.
Expected output:
Checking Multiple Conditions
You can combine checks using and or or to make more complex decisions.
Expected output:
Repeating Tasks with Loops
If you have to check ten servers, you do not want to copy and paste your check ten times. Loops let you run a block of code multiple times.
Using For Loops
A for loop goes through a list one item at a time.
Expected output:
Using While Loops
A while loop keeps running as long as a condition remains true. This is useful when waiting for a server to start.
Expected output:
Grouping Code in Functions
As your script grows, you will find yourself writing the same code over and over. You can group code into a function to make it reusable. A function takes some input, performs an action, and returns a result.
Creating a Simple Function
Let's write a function that calculates the free disk percentage.
Expected output:
Using Default Arguments
You can give arguments default values. This means you do not have to provide them every time you call the function.
Expected output:
Handling Errors Gracefully
Sometimes your script will fail. A server might be offline, or a configuration file might be missing. If you do not handle these errors, your script will crash and stop running. You can use try and except blocks to catch errors and handle them.
Expected output:
Reading and Writing Files
Many system tasks require reading configuration files or writing log messages. Python makes it easy to work with files using the with statement. The with statement makes sure the file closes automatically when you are done, even if an error happens.
Writing to a Log File
Let's write a status message to a file.
Expected output:
No output is printed to the screen, but a file named status.txt is created on your disk.
Reading from a Log File
Now let's read the status message back from the file.
Expected output:
A Real-World Example
Let's build a real tool. This script checks a list of folder paths to see if they exist and checks if they contain too many temporary files. If a directory is missing, it creates it. If it exists, it counts the files and writes the summary to a log file.
Here is how the script processes the folders:
Create a file named log_cleaner.py and add this code.
Expected output (first run when folders do not exist):
If you run the script a second time, the folders already exist, so the output changes.
Expected output (second run):
Let's read the report file to see what it wrote:
Expected output:
Common Mistakes
Forgetting to Close Files
If you open a file without the with statement, the file remains open in memory. This can lock the file and stop other processes from using it.
- The Bad Way:
- The Good Way:
Confusing Strings and Numbers
You cannot add a string and a number together directly. Python will raise an error. You must convert the number to a string first.
- The Bad Way:
- The Good Way:
Catching All Errors Without Checking
If you write an empty except: block, it catches every single error, including syntax errors or when you press Ctrl+C to stop the script. This makes debugging very difficult.
- The Bad Way:
- The Good Way:
Summary
- Python helps you replace slow, manual tasks with fast scripts that run on any system.
- Variables store details like server IPs, and lists store collections of servers.
- Dictionaries store detailed key-value configuration settings for your infrastructure.
- If statements let your script make decisions, like raising an alert when disk usage goes over a limit.
- Loops let you repeat checks across a list of servers or directories without repeating code.
- Functions group related steps into a single block that you can run multiple times.
- Try and except blocks stop your script from crashing when network or file errors happen.
- The with statement is the safest way to read and write files because it manages closing them for you.
- Splitting your automation tasks into small, readable steps makes your code easy to maintain.
- Writing clean scripts saves you time, prevents manual mistakes, and keeps your systems happy.