You might be wondering why you should learn Python for DevOps. Hereβs why:
Python is a fundamental language for DevOps, powering automation, scripting, and infrastructure management.
Today, weβre diving into Python basics to build a solid foundation for seamless automation!
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
Learning points:
πΉ Python Fundamentals β Variables, data types, operators, and control flow.
πΉ Functions & Modules β Writing reusable functions and using built-in modules.
πΉ File Handling β Reading and writing files (open(), read(), write()).
πΉ Error Handling β Using try-except blocks to handle exceptions.
πΉ Working with Lists, Tuples, and Dictionaries β Data manipulation techniques.
πΉ Installing Packages with pip β Managing external libraries.
πΉ Basic Scripting for Automation β Writing and executing Python scripts.
π§ Learn here:
Python Basics
What is the Python Programming Language?
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. Created by Guido van Rossum and released in 1991, Python emphasizes code readability with its clean and easy-to-understand syntax, which allows developers to write fewer lines of code compared to other programming languages.
Key Features:
- Easy to Learn and Use: Python has a simple syntax similar to English, making it beginner-friendly.
- Interpreted Language: Python code is executed line-by-line, which makes debugging easier.
- Dynamically Typed: Variables do not need explicit declaration, allowing more flexibility.
- Extensive Standard Library: Comes with a rich set of modules and functions for various tasks.
- Cross-Platform: Works on different operating systems such as Windows, macOS, and Linux.
- Object-Oriented and Functional: Supports multiple programming paradigms.
Common Uses:
- Web Development (using frameworks like Django and Flask)
- Data Science and Machine Learning (with libraries like Pandas, NumPy, Scikit-learn, TensorFlow)
- Automation and Scripting
- Software Development and Prototyping
- Game Development
- Internet of Things (IoT)
Why it Matters:
Python's versatility and wide range of applications have made it one of the most popular programming languages in the world. It is widely used in education, research, startups, and large enterprises, making it a valuable skill for developers and IT professionals.
Python Fundamentals
1. Variables
Variables are used to store data. You don't need to declare the type.
name = "Alice"
age = 30
is_student = True
2. Data Types
int: Integerfloat: Decimal numberstr: String (text)bool: Boolean (True/False)list: Ordered, mutable collectiontuple: Ordered, immutable collectiondict: Key-value pairs
x = 10 # int
y = 3.14 # float
name = "Bob" # str
is_active = False # bool
items = [1, 2, 3] # list
coords = (4, 5) # tuple
profile = {"name": "Alice", "age": 25} # dict
3. Operators
- Arithmetic:
+,-,*,/,//,%,** - Comparison:
==,!=,<,>,<=,>= - Logical:
and,or,not
a = 10
b = 3
print(a + b) # 13
print(a // b) # 3 (floor division)
print(a > b and b < 5) # True
4. Control Flow
- if-else
- for loop
- while loop
# if-else
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
# for loop
for i in range(3):
print(i) # 0, 1, 2
# while loop
count = 0
while count < 3:
print(count)
count += 1
These are the core fundamentals to get started with Python programming.
What Are Functions & Modules in Python?
Functions:
Functions are blocks of reusable code designed to perform a specific task. You can call a function whenever you need it, reducing repetition.
Think of functions as tools in a toolboxβyou use them when needed.
Example:
# Define a function
def greet(name):
"""This function greets the user."""
return f"Hello, {name}!"
# Call the function
print(greet("Sandip"))
Modules:
Modules are files containing Python code (functions, classes, variables) that can be imported and reused across multiple Python programs.
Think of modules as toolboxes containing many tools (functions/classes).
Example:
# Using a built-in module
import math
# Calculate the square root of a number
num = 25
result = math.sqrt(num)
print(f"Square root of {num} is {result}")
Why Use Functions & Modules?
- π Code Reusability: Write once, use many times.
- π§Ό Code Cleanliness: Breaks complex programs into smaller, manageable parts.
- π§ͺ Testing Ease: Functions and modules are easier to test independently.
- π Standard Library Access: Leverage Pythonβs built-in modules (e.g.,
math,random,datetime) for common tasks.
Example:
import random
# Generate a random number between 1 and 10
print("Random number:", random.randint(1, 10))
Using Built-in Modules Example
import datetime
# Get current date and time
now = datetime.datetime.now()
print("Current date and time:", now)
Creating and Importing a Custom Module
Step 1: Create a module file mymath.py
# mymath.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Step 2: Use it in another file
# main.py
import mymath
print(mymath.add(5, 3)) # Output: 8
print(mymath.subtract(5, 3)) # Output: 2
π File Handling in Python
File handling allows you to read from and write to files using built-in Python functions. It is essential for working with configuration files, logs, reports, or data storage.
Basic File Handling Functions
open()
Used to open a file. It returns a file object.
# Open a file in read mode
file = open("example.txt", "r")read()
Reads content from the file.
# Read the contents of the file
content = file.read()
print(content)
file.close()write()
Writes content to a file. Use mode 'w' (write) or 'a' (append).
# Open a file in write mode and write to it
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("Welcome to file handling in Python.")
file.close()Using with Statement
Automatically handles closing the file.
# Using with statement for reading
with open("example.txt", "r") as file:
print(file.read())
# Using with statement for writing
with open("example.txt", "a") as file:
file.write("\nThis is an appended line.")Python Error Handling β Using try-except Blocks
What is Error Handling?
Error handling in Python helps manage unexpected issues (called exceptions) that arise during code execution, such as file not found, division by zero, or accessing a variable that doesnβt exist.
Instead of crashing, your program can catch and handle the error gracefully.
try-except Syntax
try:
# Code that may raise an error
risky_operation()
except SomeError:
# Code that runs if an error occurs
handle_error()
Common Example: Division by Zero
try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
Catching Multiple Exceptions
try:
with open("example.txt") as file: # closes the file even if a later line fails
num = int(file.read())
result = 100 / num
except FileNotFoundError:
print("File not found.")
except ValueError:
print("File doesn't contain a valid number.")
except ZeroDivisionError:
print("Division by zero is not allowed.")Using else and finally
else: Runs only if no exception occursfinally: Always runs, whether an error occurred or not
try:
num = int(input("Enter number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful. Result:", result)
finally:
print("Execution completed.")
π¦ Working with Lists, Tuples, and Dictionaries
Lists β Ordered, Mutable Sequences
Lists are used to store multiple items in a single variable. They are ordered and mutable (can be changed).
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(fruits[1]) # Output: banana
# Adding elements
fruits.append("orange")
# Removing elements
fruits.remove("banana")
# Iterating over a list
for fruit in fruits:
print(fruit)
Tuples β Ordered, Immutable Sequences
Tuples are like lists but immutable (cannot be changed once created).
# Creating a tuple
coordinates = (10.5, 20.8)
# Accessing elements
print(coordinates[0]) # Output: 10.5
# Tuple unpacking
x, y = coordinates
print("X:", x, "Y:", y)
Dictionaries β Key-Value Pairs
Dictionaries store data as key-value pairs. They are mutable and great for quick lookups. Since Python 3.7 they also keep keys in the order you inserted them.
# Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Accessing values
print(person["name"]) # Output: Alice
# Adding/Updating values
person["age"] = 31
person["profession"] = "Engineer"
# Removing a key
del person["city"]
# Iterating through dictionary
for key, value in person.items():
print(key, ":", value)
In Short:
| Data Type | Ordered | Mutable | Allows Duplicates | Syntax Example |
|---|---|---|---|---|
| List | Yes | Yes | Yes | [1, 2, 3] |
| Tuple | Yes | No | Yes | (1, 2, 3) |
| Dictionary | Yes (insertion order) | Yes | No (keys) | {"key": "value"} |
Installing Packages with pip β Managing External Libraries
What is pip?
pip is the package installer for Python. It allows you to install, upgrade, and uninstall third-party libraries from the Python Package Index (PyPI).
Install packages inside a virtual environment. Recent Ubuntu, Debian and Homebrew Pythons refuse system-wide pip install with an "externally-managed-environment" error:
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activateInstalling a Package
pip install requests
This installs the requests library used for HTTP requests.
Example:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Installing a Specific Version
pip install requests==2.28.1
This installs version 2.28.1 of the requests library.
Upgrading a Package
pip install --upgrade requests
Uninstalling a Package
pip uninstall requests
Listing Installed Packages
pip list
Freezing Requirements to a File
pip freeze > requirements.txt
This creates a requirements.txt file with exact versions of all installed packages.
Installing from requirements.txt
pip install -r requirements.txt
In-short:
| Command | Description |
|---|---|
pip install package_name |
Installs a new package |
pip install package_name==version |
Installs specific version |
pip install --upgrade package_name |
Upgrades the package |
pip uninstall package_name |
Uninstalls the package |
pip freeze > requirements.txt |
Saves all installed packages to a file |
pip install -r requirements.txt |
Installs packages from a requirements file |
Basic Scripting for Automation β Writing and Executing Python Scripts
What is Python Scripting?
Python scripting refers to writing small programs (scripts) to automate repetitive tasks, such as file management, data parsing, sending emails, or monitoring systems.
Writing a Basic Script
Create a file named automate.py:
# automate.py
import os
def create_folder(name):
if not os.path.exists(name):
os.makedirs(name)
print(f"Folder '{name}' created.")
else:
print(f"Folder '{name}' already exists.")
# Call the function
create_folder("backup")
Running the Script
From the terminal:
python automate.py
This executes your automation script.
Another Example: Rename Files
import os
# Rename all .txt files to .bak
for filename in os.listdir("."):
if filename.endswith(".txt"):
new_name = filename.replace(".txt", ".bak")
os.rename(filename, new_name)
print(f"Renamed: {filename} -> {new_name}")
Scheduled Automation
Use OS tools like cron (Linux/macOS) or Task Scheduler (Windows) to run scripts on a schedule.
Example cron job to run a script every day at 9AM:
0 9 * * * /usr/bin/python3 /home/user/automate.py
ποΈ Resources:
π Python Basics β Python Official Docs
π Python for Beginners β W3Schools Python Tutorial
π Learn Python the Right Way β Real Python
π Automating Tasks with Python β Automate the Boring Stuff
Initial Tasks:
β
Task 1: Install Python (Check with python --version) and set up a virtual environment (venv).
β
Task 2: Install VS Code or PyCharm for a better coding experience.
β
Task 3: Write a simple Python script that prints "Hello, DevOps!".
β
Task 4: Explore built-in data types (int, float, str, list, tuple, dict) and perform basic operations.
β
Task 5: Write a Python function that takes two numbers as input and returns their sum.
β
Task 6: Use Pythonβs os and sys modules to interact with the system.
π₯ Challenges
πΉ Challenge 1: Create a Python program that accepts a userβs name as input and prints a greeting message.
πΉ Challenge 2: Write a script that reads a text file and counts the number of words in it.
πΉ Challenge 3: Create a Python script that generates a random password of 12 characters.
πΉ Challenge 4: Implement a Python program that checks if a number is prime.
πΉ Challenge 5: Write a script that reads a list of server names from a file and pings each one.
πΉ Challenge 6: Use the requests module to fetch and display data from a public API (e.g., JSONPlaceholder).
πΉ Challenge 7: Automate a simple task using Python (e.g., renaming multiple files in a directory).
πΉ Challenge 8: Create a Python script that monitors CPU and memory usage every 5 seconds.
πΉ Challenge 9: Write a Python program that creates a user in Linux using subprocess and verifies the creation.
β Solutions:
π Challenge 1: Greeting Script
# greet.py
name = input("Enter your name: ")
print(f"Hello, {name}! Welcome to the DevOps world! π")
Run:
python greet.py
π Challenge 2: Word Count in File
# word_count.py
file_name = input("Enter the file name: ")
try:
with open(file_name, "r") as file:
content = file.read()
word_count = len(content.split())
print(f"β
The file '{file_name}' contains {word_count} words.")
except FileNotFoundError:
print(f"β Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"β An error occurred: {e}")
Run:
echo "DevOps is about automation, collaboration, and efficiency." > sample.txt
python word_count.py
Bonus:
file_name = input("Enter the file name: ")
try:
word_count = 0
with open(file_name, "r") as file:
for line in file:
word_count += len(line.split())
print(f"β
The file '{file_name}' contains {word_count} words.")
except FileNotFoundError:
print(f"β Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"β An error occurred: {e}")
π Challenge 3: Random Password Generator
# generate_password.py
import secrets
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(characters) for _ in range(length))
return password
print(f"π Your secure password: {generate_password()}")
Bonus:
import secrets
import string
def generate_password(length):
if length < 8:
print("β Password length should be at least 8 characters for security.")
return None
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(secrets.choice(characters) for _ in range(length))
length = int(input("Enter password length (min 8): "))
password = generate_password(length)
if password:
print(f"π Your secure password: {password}")π Challenge 4: Prime Number Checker
# check_prime.py
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
try:
num = int(input("Enter a number: "))
if is_prime(num):
print(f"β
{num} is a prime number.")
else:
print(f"β {num} is not a prime number.")
except ValueError:
print("β Please enter a valid integer.")
π Challenge 5: Ping Servers from File
# ping_servers.py
import platform
import subprocess
import sys
def ping_server(server):
count_flag = "-n" if platform.system().lower() == "windows" else "-c"
# pass arguments as a list: no shell, so a hostname can't inject commands,
# and DEVNULL works on Windows too (unlike "> /dev/null")
result = subprocess.run(["ping", count_flag, "1", server],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return result.returncode == 0
try:
with open("servers.txt", "r") as file:
servers = [line.strip() for line in file if line.strip()]
except FileNotFoundError:
print("β Error: servers.txt not found!")
sys.exit(1)
for server in servers:
status = "β
Reachable" if ping_server(server) else "β Unreachable"
print(f"{server}: {status}")Bonus - Log Results:
with open("ping_results.log", "w") as log_file:
for server in servers:
if server:
status = "β
Reachable" if ping_server(server) else "β Unreachable"
log_file.write(f"{server}: {status}\n")
print(f"{server}: {status}")
π Challenge 6: CRUD Operations with Requests
# crud_call.py
import requests
API_URL = "https://jsonplaceholder.typicode.com/posts"
TIMEOUT = 10
def get_post(post_id):
response = requests.get(f"{API_URL}/{post_id}", timeout=TIMEOUT)
response.raise_for_status()
post = response.json()
print(f"π GET post {post_id}: {post['title']}")
return post
def create_post():
payload = {"title": "Learning DevOps", "body": "Python + REST APIs", "userId": 1}
response = requests.post(API_URL, json=payload, timeout=TIMEOUT)
response.raise_for_status()
post = response.json()
print(f"π Created post with id {post['id']}")
return post["id"]
def update_post(post_id):
payload = {"id": post_id, "title": "Updated title", "body": "Updated body", "userId": 1}
response = requests.put(f"{API_URL}/{post_id}", json=payload, timeout=TIMEOUT)
response.raise_for_status()
print(f"βοΈ Updated post {post_id}: {response.json()['title']}")
def delete_post(post_id):
response = requests.delete(f"{API_URL}/{post_id}", timeout=TIMEOUT)
response.raise_for_status()
print(f"ποΈ Deleted post {post_id} (HTTP {response.status_code})")
if __name__ == "__main__":
get_post(1)
create_post()
# JSONPlaceholder only fakes writes (the new post isn't stored),
# so update and delete an existing post instead
update_post(1)
delete_post(1)π Challenge 7: Bulk Rename Files
# rename_files.py
import os
import sys
directory = "test_files"
prefix = "renamed_"
if not os.path.isdir(directory):
print(f"β Error: Directory '{directory}' not found!")
sys.exit(1)
for count, filename in enumerate(sorted(os.listdir(directory)), start=1):
old_path = os.path.join(directory, filename)
if os.path.isfile(old_path):
extension = os.path.splitext(filename)[1] # keep .log, .csv, ... as they were
new_name = f"{prefix}{count}{extension}"
os.rename(old_path, os.path.join(directory, new_name))
print(f"β
Renamed: {filename} β {new_name}")
print("π Renaming completed!")π Challenge 8: Monitor CPU & Memory
# monitor_resources.py (pip install psutil)
import psutil
import time
def monitor_resources(interval=5):
print("π Monitoring CPU and Memory usage... (Press Ctrl+C to stop)\n")
try:
while True:
cpu_usage = psutil.cpu_percent(interval=1) # measures over 1 second
memory_usage = psutil.virtual_memory().percent
print(f"π₯οΈ CPU Usage: {cpu_usage}% | π§ Memory Usage: {memory_usage}%")
time.sleep(interval - 1)
except KeyboardInterrupt:
print("\nβ Monitoring stopped.")
if __name__ == "__main__":
monitor_resources()Bonus - Log to File:
import time
from datetime import datetime
import psutil
with open("resource_usage.log", "a") as log_file:
while True:
cpu = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory().percent
log_file.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} CPU={cpu}% MEM={mem}%\n")
log_file.flush() # write now, so tail -f shows it
time.sleep(4)π Challenge 9: Create Linux User with Subprocess
# create_user.py
import subprocess
def create_user(username):
try:
subprocess.run(["id", username], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f"β
User '{username}' already exists.")
return
except subprocess.CalledProcessError:
pass
try:
subprocess.run(["sudo", "useradd", "-m", "-s", "/bin/bash", username], check=True)
print(f"β
User '{username}' created successfully.")
except subprocess.CalledProcessError:
print(f"β Failed to create user '{username}'. Ensure you have sudo privileges.")
return
try:
subprocess.run(["id", username], check=True)
print(f"β
Verification successful: '{username}' exists in the system.")
except subprocess.CalledProcessError:
print(f"β Verification failed: '{username}' does not exist.")
username = input("Enter the username to create: ")
create_user(username)
How to Participate?
β
Complete the tasks and challenges.
β
Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
β
Share the above in a LinkedIn post tagging me (Sandip Das) and use #60DaysDevOps to engage with the community
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion