πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

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:


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: Integer
  • float: Decimal number
  • str: String (text)
  • bool: Boolean (True/False)
  • list: Ordered, mutable collection
  • tuple: Ordered, immutable collection
  • dict: 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 occurs
  • finally: 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\activate

Installing 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:

Share this post