
Projects to do with Python
Daily Joke Generator Program
Instructions
An example of fun projects to do with Python is this daily joke generator program for every day of the week. Your task is to create a Python program that displays a diffent joke if you run it on different days.
Write a script that calls the officials joke API (“https://official-joke-api.appspot.com/random_ten”) and prints the joke corresponding to the day of the week when the API is called. For example, if today is monday, the program must display the joke corresponding to the smallest id found in the response. If today is wednesday, the program must display the joke corresponding to the third id in the ranking. Use the “id” of the joke to sort the file from smallest to largest.
In this Python challenge for intermediates you will practice many important topics such as API calls with the request module, the datetime library and json files treatment with Python.
Json Sample
[{'type': 'general',
'setup': 'I just watched a documentary about beavers.',
'punchline': 'It was the best dam show I ever saw',
'id': 41},
{'type': 'general',
'setup': 'Did you hear about the runner who was criticized?',
'punchline': 'He just took it in stride',
'id': 94},
{'type': 'general',
'setup': 'How many seconds are in a year?',
'punchline': '12. January 2nd, February 2nd, March 2nd, April 2nd.... etc',
'id': 143},
{'type': 'general',
'setup': 'What do you do on a remote island?',
'punchline': 'Try and find the TV island it belongs to.',
'id': 229},
Guidelines
- Import the libraries
- Get the current day of the week.
- Call the official jokes API:
- Sort the jokes JSON by the “id”
- Select the joke based on the current day of the week:
Source code
## Import the necessary libraries
import datetime
import requests
## Get the current day
current_day = datetime.datetime.today().weekday()
## Call the API
response = requests.get("https://official-joke-api.appspot.com/random_ten")
jokes = response.json()
## Sort the file
jokes_sorted = sorted(jokes, key=lambda x: x["id"])
## Seelct the joke corresponding to the current day by rank
selected_joke = jokes_sorted[current_day]
# Display the joke
print(selected_joke['setup'])
print(selected_joke["punchline"])
Expected Output
How many seconds are in a year? 12. January 2nd, February 2nd, March 2nd, April 2nd.... etc
If you wish to keep improving your skills with Python projects