Task 1: Define a Function to Calculate Factorial
I started with defining a Python function to calculate the factorial of a number. Here's how the function looks:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Then, I tested it with different inputs to ensure its accuracy:
print(f"Factorial of 5: {factorial(5)}") # Expected output: 120
print(f"Factorial of 0: {factorial(0)}") # Expected output: 1
print(f"Factorial of 7: {factorial(7)}") # Expected output: 5040
Task 2: Creating a Module for New Math Operations
Next, I worked on creating a module that handles different mathematical operations: division, modulus, and exponentiation. I created a file named math_operations.py and added the following functions:
# math_operations.py
def divide(a, b):
return a / b
def modulus(a, b):
return a % b
def exponentiate(a, b):
return a ** b
After setting up the module, I tested these functions in a separate script:
Importing the math_operations module is crucial because it allows you to reuse the defined functions across different scripts without duplicating code.
import math_operations
print(f"Division: {math_operations.divide(10, 2)}") # Expected output: 5.0
print(f"Modulus: {math_operations.modulus(10, 3)}") # Expected output: 1
print(f"Exponentiation: {math_operations.exponentiate(2, 3)}") # Expected output: 8
Task 3: Handling Exceptions Gracefully
Used Python's try-except blocks, to handle potential errors like a file not being found or a division by zero without crashing.
try:
with open('nonexistent_file.txt', 'r') as file:
data = file.read()
except FileNotFoundError:
print("The file was not found. Please check the filename and try again.")
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Task 4: Making HTTP GET Requests
In the provided code snippet, the script makes an HTTP GET request to retrieve data from a web API.
You can change this URL to any API or website that returns JSON data. For instance, you could use:
'https://api.github.com/users/octocat' (to get information about a GitHub user)
import requests
response = requests.get('https://api.github.com/users/octocat') # Change this URL to any valid API endpoint
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
Task 5: Interacting with a Mock REST API
This task demonstrates how to interact with a REST API using Python, showcasing how to fetch and update data from a server.
By changing the URLs and data, you can interact with any REST API, making this a versatile skill for developers working with web services.
import requests
# API endpoint to update a specific post
url = 'https://jsonplaceholder.typicode.com/posts/1'
# Data to update in the record
updated_data = {
"id": 1,
"title": "Updated Title",
"body": "Updated body content",
"userId": 1
}
# Sending an HTTP PUT request to update the record
response = requests.put(url, json=updated_data)
# Check if the update was successful
if response.status_code == 200:
print("Record updated successfully!")
print(response.json()) # Display the updated record
else:
print(f"Failed to update the record. Status code: {response.status_code}")