# Week 3 --- Python Practice with Modules, Dates, JSON, Pip, Error Handling, and More
This week, I continued practicing Python through structured tasks, assignments, and assessments. These exercises focused on:
- Modules (math, datetime, json)
- Dates and times
- JSON conversions
- Pip and package management
- Error handling
- User input
- Virtual environments
Below is my learning journey with my exact code and detailed explanations.
Tasks (10)
1. Import the math module and calculate the square root of 144
import math
math.sqrt(144)
2. Print the current date and time using the datetime module
from datetime import datetime
print(datetime.now())
3. Convert a Python dictionary into a JSON string
import json
python_dictionary = {'name':'habeeb','id':1 }
json_string = json.dump(python_dictionary)
print(json_string)
4. Convert a JSON string into a Python dictionary
import json
json_string = '{"name":"habeeb","id":1}'
python_dict = json.load(json_string)
print(python_dict)
5. Use pip to check the version installed
!pip --version
6. Write a program that takes a user's birth year as input and calculates their age
from datetime import datetime
birth_year = int(input("Enter your birth year: "))
current_year = datetime.now().year
age = current_year - birth_year
print("Your age is", age, "years")
7. Write a program that catches a division by zero error
try:
number = int(input("Enter a number: "))
print(100 / number)
except ZeroDivisionError:
print("Division by zero is not allowed")
8. Create and activate a virtual environment, then install the requests package
python -m venv myvirtualenv
myvirtualenv\Scripts\activate
pip install requests
9. Use the math.pi constant to calculate the area of a circle
import math
radius = 7
area = math.pi * (radius**2)
print(area)
10. Write a program that reads a JSON file into a Python object
import json
with open("students.json", "r") as file:
data = json.load(file)
print(data)
Assignments (5)
1. Math Quiz Program (5 random questions)
import random
# Operators available
operators = ["+", "-", "*", "/"]
# Function to generate a random question
def question_generator():
number1 = random.randint(30, 60)
number2 = random.randint(1, 10)
# randomly choose an operator
chosen_operator = random.choice(operators)
#formulate question
question = f"{number1} {chosen_operator} {number2}"
#evaluate the question and get the correct answer
answer = eval(question)
return (question, answer)
# The Quiz
score = 0
print("Math Quiz! Answer five(5) questions.\n")
for i in range(0, 5):
question, correct_answer = question_generator()
print(f"Question {i+1}: {question} = ")
user_answer = input("Enter your answer: ")
if float(user_answer) == correct_answer:
print("Bravo!\n")
score += 1
else:
print(f"You are wrong! The correct answer is {correct_answer}\n")
# Total score
print(f"End of Quiz! Your score is: {score}/5")
2. Error Handling System (100 divided by user input)
try:
num = float(input("Enter a number to divide 100 by: "))
print(100 / num)
except ValueError:
print("Invalid input! Enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero")
3. Date Calculator (days until next birthday)
import json
# Creating a list of student records
students_list = [
{"name": "Habeeb", "age": 10, "grade": "7"},
{"name": "Olatunde", "age": 14, "grade": "8"},
{"name": "Babatunde", "age": 16, "grade": "9"}]
# Saving the list to a JSON file
with open("students_list.json", "w") as students_file:
json.dump(students_list, students_file, indent=3)
# Reading the JSON file back into a Python object
with open("students_list.json", "r") as students_file:
students = json.load(students_file)
# Showing the stored object in python
for student in students:
print(student)
`
5. Save student records into JSON file
import json
students = [
{"name": "Habeeb", "age": 10, "grade": "9"},
{"name": "Olatunde", "age": 14, "grade": "10"},
]
with open("students.json", "w") as f:
json.dump(students, f, indent=4)
with open("students.json", "r") as f:
data = json.load(f)
print(data)
Assessments (15)
I worked through more 15 key questions covering modules, JSON, pip, exceptions, math, GCD, virtual environments, and more.
Some highlights:
- Difference between module and package : module is a single
.pyfile; package is a collection of modules with__init__.py. - math.pi for circle calculations.
- pip install numpy==1.23.5 : installs a specific version.
- math.gcd(x, y) : finds greatest common divisor.
- date.today() →:gets today's date.
- round(76.988, 2) : rounds to 2 decimal places.
- json.JSONDecodeError : occurs if JSON content is invalid.
Reflection
This week was packed with practical exercises. I learned:
- To import and use standard Python modules effectively.
- How to handle JSON data interchange.
- Why pip and virtual environments are essential for managing dependencies.
- How to build small, useful programs like quizzes, calculators, and error-handling systems.
- How to handle exceptions safely to make programs more robust.
My big takeaway: Practicing with real code and error handling gave me the confidence to apply Python for problem solving in everyday tasks.