Intermediate Python Concepts for Automation(Day12)

Araiz bin Saqib
4 min readJul 4, 2024

--

Welcome to Day-12 of your DevOps journey! Continuing our DevOps series, today we will be diving into Intermediate Python Concepts for Automation.

In our previous discussion, we covered Python Basics and Automation Fundamentals. If you haven’t read it yet, you can check it out [here].

Moving on in the journey, today we will be looking at functions, modules, error handling, debugging, and APIs and networking.

Starting with functions, I hope you already know how to create and call a function. If not, don’t worry about it. Let’s have a look at the structure of a function calculating a factorial.

Now, let’s get started. I’ll be using the VS Code IDE, but feel free to use your preferred IDE.

1) Functions and Modules

  • Defined a function to calculate factorial of a number and tested it with different inputs.

Function to Calculate Factorial

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Testing the function with different inputs
print(factorial(4)) # Output: 24
print(factorial(7)) # Output: 5040
print(factorial(10)) # Output: 3628800

Module for Basic Math Operations

  • Created a module containing functions for basic math operations (addition, subtraction, multiplication).

Create a file named math_operations.py with the following content:

def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b

To use this module, you can import it in another script:

import math_operations as mo
print(mo.add(10, 5))       # Output: 15
print(mo.subtract(10, 5)) # Output: 5
print(mo.multiply(10, 5)) # Output: 50
print(mo.divide(10, 5)) # Output: 2

2) Error Handling and Debugging

Handle Exceptions Gracefully

  • Modified an existing script to handle exceptions gracefully (e.g., file not found, division by zero).

Here’s an existing script modified to handle exceptions:

def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Error: Division by zero is not allowed."
except TypeError:
return "Error: Invalid input type."
else:
return result
print(divide_numbers(10, 0))  # Output: Error: Division by zero is not allowed.
print(divide_numbers(10, 'a')) # Output: Error: Invalid input type.
print(divide_numbers(10, 2)) # Output: 5.0

Debug a Script using pdb

  • Debugged a script using pdb or an IDE to identify and fix logical errors.

Another method to debug code is by using the built-in Python debugger. We can set breakpoints using the pdb library. Although both work similarly, in Python versions 3.7 and above, we can use the breakpoint() function, while in older versions, we use the following line to add breakpoints.

import pdb
pdb.set_trace()

Let’s debug the following script:

import pdb
def buggy_function(a, b):
pdb.set_trace() # This will start the debugger
result = a + b
return result
print(buggy_function(10, '5'))

Run this script and use pdb commands to debug. For example, you can use n to go to the next line, c to continue, and p to print variables.

3) Networking and APIs

What is an API? API stands for Application Programming Interface. It’s a set of rules that allows software programs to communicate with each other by sending requests and receiving responses. APIs are a key tool for application integration, enabling applications and systems from different vendors to work together seamlessly. They also help developers avoid redundant work by incorporating existing functions into new applications. APIs are characterized by their adherence to specific standards, such as HTTP and REST, making them developer-friendly and easily accessible.

HTTP GET Requests using requests

import requests
def fetch_data(url):
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
return response.json() # Assuming the response is in JSON format
except requests.exceptions.HTTPError as http_err:
return f"HTTP error occurred: {http_err}"
except Exception as err:
return f"An error occurred: {err}"
url = 'https://jsonplaceholder.typicode.com/posts'
print(fetch_data(url))

Interact with a Mock REST API

import requests
base_url = 'https://jsonplaceholder.typicode.com/posts'def fetch_post(post_id):
response = requests.get(f"{base_url}/{post_id}")
return response.json()
def update_post(post_id, data):
response = requests.put(f"{base_url}/{post_id}", json=data)
return response.json()
# Fetch a post
post = fetch_post(1)
print(post)
# Update a post
updated_post = update_post(1, {'title': 'Updated Title', 'body': 'Updated body content'})
print(updated_post)

--

--