Week 13 Tutorial: Modules and Interacting with the Web (APIs)
Problem 1: The Exam Countdown Timer
Problem Statement: You are writing a simple utility program to help students track how much time they have left before their final exam.
Write a program that:
- Imports the
datetimemodule (you may alias it asdtif you wish). - Asks the user to input the year, month, and day of their exam separately.
- Creates a
dateobject for the exam date using the user’s input. - Gets the current date from the computer’s system.
- Calculates the difference between the exam date and the current date.
- Checks if the exam date has already passed.
- If the exam is in the future, print:
"You have X days left to study!" - If the exam is today, print:
"Good luck! The exam is today." - If the exam is in the past, print:
"The exam was X days ago."
- If the exam is in the future, print:
Input/Output Examples:
Case 1: Exam is in the future (Assume today is 2025-12-23)
Enter exam year: 2026
Enter exam month: 1
Enter exam day: 15
You have 23 days left to study!
Case 2: Exam is in the past (Assume today is 2025-12-23)
Enter exam year: 2025
Enter exam month: 12
Enter exam day: 1
The exam was 22 days ago.
Problem 2: Where is the Space Station?
Problem Statement: The International Space Station (ISS) is constantly orbiting the Earth. There is a free, public API that provides its current coordinates in real-time.
API URL: http://api.open-notify.org/iss-now.json
Write a program that:
- Connects to the API using the
requestslibrary. - Checks if the connection was successful (Status Code 200).
- If successful, converts the response text into a Python dictionary.
- Extracts the
latitudeandlongitudefrom the nested dictionary. - Prints the location clearly.
Structure of the JSON data returned by the API:
{
"message": "success",
"timestamp": 1699982000,
"iss_position": {
"latitude": "-25.1234",
"longitude": "120.5678"
}
}
Expected Output:
Connecting to ISS satellite...
Connection Successful!
Current Location:
Latitude: -25.1234
Longitude: 120.5678
Problem 3: The Monte Carlo Dice Simulation
Problem Statement: A “Monte Carlo Simulation” is a technique used to predict the probability of different outcomes by running a simulation many times.
You are going to simulate rolling two 6-sided dice 1,000 times to analyze the distribution of the results.
Write a program that:
- Imports
randomandstatistics. - Creates an empty list called
results. - Runs a loop 1,000 times. In each iteration:
- Simulate rolling two dice (generate two random integers between 1 and 6).
- Calculate the sum of the two dice (result will be between 2 and 12).
- Append this sum to the
resultslist.
- After the loop finishes, use the
statisticsmodule to calculate:- The Mean (average) of the results.
- The Median (middle value) of the results.
- The Mode (most common value) of the results.
- Print the statistics formatted to 2 decimal places.
Hint: The statistics module has functions named mean(), median(), and mode() that take a list of numbers as an argument.
Expected Output: (Note: Numbers will vary slightly every time you run it, but should be close to these mathematical probabilities)
--- Simulation Results (1000 rolls) ---
Mean: 7.02
Median: 7.0
Mode: 7
Problem 4: Global University Search
Problem Statement: You are building a search tool for high school students looking for universities abroad. You will use the free “Hipolabs Universities API”.
API URL: http://universities.hipolabs.com/search
Write a program that:
- Asks the user to input a Country Name (e.g., “Turkey”, “Uzbekistan”, “United Kingdom”).
- Creates a parameters dictionary to pass to the API (the API expects a query parameter named
country). - Makes a
GETrequest to the API. - Parses the JSON response.
- Note: This API returns a List of dictionaries, not a single dictionary.
- Analyzes the data:
- If no universities are found (empty list), print
"No universities found for [Country]." - If found, print the Total Count of universities found.
- Print the names of the first 5 universities in the list.
- If no universities are found (empty list), print
Input/Output Examples:
Case 1: User enters “Uzbekistan”
Enter a country to search: Uzbekistan
Found 23 universities in Uzbekistan.
Here are the first 5:
1. Tashkent State Agrarian University
2. Ferghana Politechnical Institute
3. International Business School Kelajak ILMI
4. Management Development Institute of Singapore, Tashkent
5. Nukus State Teachers Training Institute
Case 2: User enters “Atlantis” (Non-existent)
Enter a country to search: Atlantis
No universities found for Atlantis.
Problem 5: The Tournament Scheduler
Problem Statement: You are organizing a Round-Robin E-Sports tournament. In this format, every team must play against every other team exactly once.
Writing nested loops to find these unique pairs without duplicates (e.g., A vs B is the same as B vs A) can be tricky. Fortunately, Python’s Standard Library has a module called itertools that solves this math problem for you.
Write a program that:
- Imports
itertoolsandrandom. - Defines a list of 6 team names (e.g., “Tigers”, “Dragons”, “Eagles”, “Sharks”, “Wolves”, “Bears”).
- Uses
random.shuffle()to mix up the list order so the schedule is different every time. - Uses the
itertools.combinations(iterable, r)function to generate all possible unique matchups.- Hint: The first argument is your list of teams. The second argument
ris the size of the group (2, because it’s a 1vs1 match).
- Hint: The first argument is your list of teams. The second argument
- Iterates through these combinations and prints a numbered schedule.
- Prints the total number of matches calculated.
Expected Output:
--- Tournament Schedule ---
Match 1: Dragons vs Wolves
Match 2: Dragons vs Tigers
Match 3: Dragons vs Bears
...
Match 14: Tigers vs Sharks
Match 15: Eagles vs Sharks
---------------------------
Total Matches to play: 15
Problem 6: The Random User Database Builder
Problem Statement: You are testing a database and need to generate fake user data. Instead of typing it manually, you will use the “Random User Generator” API to fetch profiles and save them to a file.
API URL: https://randomuser.me/api/?results=10&nat=us
(This fetches 10 random users from the US).
Write a program that:
- Makes a
GETrequest to the API. - Parses the JSON response.
- Note: The user data is inside a key called
"results", which is a list. - Challenge: The name is nested (e.g.,
user['name']['first']).
- Note: The user data is inside a key called
- Extracts the following fields for each user: First Name, Last Name, Email, City.
- Uses the
csvmodule to write this data into a new file calledfake_users.csv. - Includes a header row in the CSV:
first_name,last_name,email,city.
JSON Structure Hint:
{
"results": [
{
"name": { "first": "brad", "last": "gibson" },
"email": "brad.gibson@example.com",
"location": { "city": "kilcoole", ... }
}
]
}
Expected Output (Console):
Fetching data from API...
Successfully fetched 10 users.
Writing to fake_users.csv...
Done!
Expected Output (File: fake_users.csv):
first_name,last_name,email,city
brad,gibson,brad.gibson@example.com,kilcoole
alice,smith,alice.smith@example.com,austin
...
Problem 7: The "Open Library" Analyzer
Problem Statement: You are building a tool for a librarian to analyze search results from the Open Library. You want to search for a specific subject and find the thickest book (highest page count) and the oldest book (earliest publication year) from the results.
API URL: https://openlibrary.org/search.json
Critical Requirement:
By default, this API returns too much data. To get the specific fields we need, you must add a parameter called fields to your request with the value: title,author_name,first_publish_year,number_of_pages_median.
Write a program that:
- Asks the user for a Search Subject (e.g., “Python”, “Robotics”).
- Sends a GET request to the API with three parameters:
q: The subject the user entered.limit:10(to keep the data manageable).fields:title,author_name,first_publish_year,number_of_pages_median(This is required to get the page counts!).
- Parses the JSON response. The list of books is under the key
"docs". - Loops through the books to find:
- The book with the maximum
number_of_pages_median. - The book with the minimum
first_publish_year.
- The book with the maximum
- Challenge: Real-world data is messy!
- Some books do not have the
number_of_pages_mediankey. - Some books do not have the
first_publish_yearkey. - Your code must strictly ignore books that are missing this data to avoid crashing.
- Some books do not have the
- Prints the title and relevant statistic for the winner in each category.
Expected Output:
Enter a subject: Artificial Intelligence
Fetching top 10 results...
--- Analysis Results ---
Thickest Book:
Title: Artificial intelligence
Pages: 1144
Oldest Book:
Title: Artificial intelligence
Year: 1977
Problem 8: The International Expense Report
Problem Statement: You have returned from a business trip with receipts in different currencies (Euros, Pounds, Yen). You need to generate a final expense report in USD.
Part 1: The Setup
Create a file named expenses.csv in your project folder with the following content (including the header):
Item,Amount,Currency
Taxi,50,EUR
Lunch,2500,JPY
Hotel,120,GBP
Coffee,5,EUR
Gift,30,USD
Part 2: The Program
API URL: https://open.er-api.com/v6/latest/USD
(This is a free, open API that returns exchange rates relative to USD).
Write a program that:
- Fetches current exchange rates from the API.
- Creates a Lookup Dictionary from the API response (e.g.,
{'EUR': 0.92, 'JPY': 145.5, ...}). Note: The API gives the rate of 1 USD in other currencies. To convert TO USD, you usually divide by the rate. - Reads your
expenses.csvfile using thecsvmodule. - For each row in the CSV:
- Get the Amount and Currency.
- Find the correct exchange rate in your lookup dictionary.
- Convert the amount to USD.
- Calculates the Grand Total in USD.
- Writes a new file named
expense_report.txtcontaining the converted list and the total.
Logic Hint for Conversion:
If the API says USD -> EUR is 0.92:
- To convert 50 EUR to USD:
50 / 0.92 = $54.34 - Make sure to handle the case where the currency is already USD!
Expected Output (Console):
Fetching exchange rates...
Processing expenses.csv...
Report written to expense_report.txt
Total Expenses: $270.84
Expected Output (File: expense_report.txt):
Item: Taxi | Original: 50.0 EUR | USD: $58.58
Item: Lunch | Original: 2500.0 JPY | USD: $15.90
Item: Hotel | Original: 120.0 GBP | USD: $160.49
Item: Coffee | Original: 5.0 EUR | USD: $5.86
Item: Gift | Original: 30.0 USD | USD: $30.00
--------------------------------------------------
GRAND TOTAL: $270.84
This content will be available starting December 23, 2025.