Whether you love them or hate them, dads always have them at the ready. It’s the classic dad joke. 

We’ve turned dad’s favorite jokes into a Python app, so anyone can tell a great dad joke at any time. The Random Dad Joke App picks an awesome dad joke from a database and shows it to you so you can deliver the punchline. These jokes are so bad and corny, they might actually make you laugh! 

Complete this Python coding tutorial to build your own Random Dad Joke App.

Make your friends and family laugh with a few funny dad jokes.

See the completed Random Dad Joke App.

What you need:

1. Text editor

We’ll be using the CodeWizardsHQ editor to write and run our Python code. If you’re a CodeWizardsHQ student, download the x_hour_of_code_2022 project for the completed code. 

You can also use an online text editor like replit that allows you to author and run Python programs in a web browser.

2. An empty Python file

Create a new empty Python file and add your code there. 

Our file is named main.py, and if you’re a CWHQ student you must use this name. If you’re using another platform to write and execute your code, you can choose whichever name you like.

This tutorial is for beginner Python programmers ages 11+. Let’s get started!

Step 1: Display a welcome message to the user

Display a message to the users that explains how the Random Dad Joke app works.

welcome_message = """
    Welcome to the 'Random Dad Joke' app!
    This app uses an API to fetch a random setup
    and punchline to a dad joke. The setup will
    be displayed to you, and if you guess the punchline,
    a message like "That's correct!" will be displayed.
    Otherwise, you'll be shown the punchline.
"""
welcome_message = """
  ...
"""
print(welcome_message)

Hint: Change the message inside the “”” to personalize your welcome message.

Step 1 Output:

python tutorial step 1

Step 2: Display the options the app accepts

Show the user the possible options the app accepts and prompt them for their choice.

welcome_message = """
  ...
"""
options = "(1) Get Dad Joke (2) Exit: "
print(welcome_message)
print(welcome_message)

while True:
    user_choice = int(input(options))
while True:
    user_choice = int(input(options))
    break

Hint: Create more options as an additional challenge.

Step 2 Output:

python tutorial step 2

Step 3: Process the user’s choice

Next, we want the users to choose an option by entering the number 1 or 2 and we will execute their choice. 


options = "(1) Get Dad Joke (2) Exit: "
GET_JOKE = 1
EXIT = 2

print(welcome_message)
while True:
    ...
while True:
    user_choice = int(input(options))
    break  # Remove this!
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        pass
    elif user_choice == EXIT:
        break

Hint: Create more options as an additional challenge.

Step 3 Output:

python tutorial step 3

Step 4: Get a random dad joke from the Dad Jokes API

Now, let’s get retrieve some hilarious dad jokes! We will be connecting to a CodeWizardsHQ API that holds a database of jokes.

def get_random_joke():
    BASE_URL = "https://projects.flask.cwhq-apps.com/dad-joke-api"
    endpoint = "/random/jokes"
    request_url = f"{BASE_URL}{endpoint}"

welcome_message = """
    ...
"""
from urllib.request import urlopen

def get_random_joke():
    ...
from urllib.request import urlopen

def get_random_joke():
    BASE_URL = "https://projects.flask.cwhq-apps.com/dad-joke-api"
    endpoint = "/random/jokes"
    request_url = f"{BASE_URL}{endpoint}"

    with urlopen(request_url) as response:
        joke = response.read()
def get_random_joke():
    ...
    with urlopen(request_url) as response:
        joke = response.read()
    print(joke)
while True:
    user_choice = int(input(options))
    if user_choice == GET_JOKE:
        get_random_joke()
    elif user_choice == EXIT:
        break

Hint: If you see a really long response when trying to get a dad joke, wait about 10 seconds and then try again. The API has to “wake up” from being asleep if it hasn’t been used recently!

Step 4 Output:

python tutorial step 4

Step 5: Correctly format the data from the Dad Jokes API

Now we have the information (the joke) from the API, we need to format it in a way users can read it.

from urllib.request import urlopen
from json import loads

def get_random_joke():
    ...
def get_random_joke():
    ...

    with urlopen(request_url) as response:
        joke = loads(response.read())

    print(joke)

Hint: An API is an application programming interface which allows interactions between multiple software programs. Programmers (you!) then have access to data and info from external software (CodeWizardsHQ’s dad joke database).

Step 5 Output:

python tutorial step 5

Step 6: Return the setup and punchline from the get_random_joke() function

Now, let’s separate the setup and the punchline as we will want to present them independently later. 

def get_random_joke():
    ...
    with urlopen(request_url) as response:
        joke = loads(response.read())
    print(joke) # Remove this!
def get_random_joke():
    ...
    with urlopen(request_url) as response:
        joke = loads(response.read())
    return joke["setup"], joke["punchline"]
while True:
    user_choice = int(input(options))
    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
    elif user_choice == EXIT:
        break
while True:
    user_choice = int(input(options))
    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
        print(f"{setup=}")
        print(f"{punchline=}")
    elif user_choice == EXIT:
        break

Hint: An f-string is a formatted string literal. It lets you include the value of a variable inside a string with the prefix “f”.

Step 6 Output:

python tutorial step 6

Step 7: Ask the user to guess the punchline and tell them if they’re right or wrong

After the user selects 2, we will prompt them to guess the punchline and also check if they guessed correctly.

while True:
    user_choice = int(input(options))
    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()

        print(f"{setup=}")      # Remove this!
        print(f"{punchline=}")  # Remove this!

    elif user_choice == EXIT:
        break
while True:
    user_choice = int(input(options))
    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
        print(setup)
        user_guess = input("Guess the punchline: ")
    elif user_choice == EXIT:
        break
while True:
    user_choice = int(input(options))
    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
        print(setup)
        user_guess = input("Guess the punchline: ")

        if user_guess == punchline:
            print("That's correct!")
        else:
            print("Sorry, that wasn't the punchline.")
            print(f"The punchline was: {punchline}")

    elif user_choice == EXIT:
        break

Hint: Change the text inside the print() function to customize your user message.

Step 7 Output:

python tutorial step 7

Your app is complete!

Check out the finished Random Dad Joke App.

python tutorial dad jokes complete

Download the project files and open main.py to view the completed project.

Now, you’re ready with a great dad joke in every situation. 

If you want to build games and apps in Python, join CodeWizardsHQ’s live coding classes for kids. It’s the most fun and effective way for kids to learn Python and advance to a real-world coding internship. 

Students in our middle school and high school core track start by learning fundamental coding concepts in Python. They work with a live, expert instructor who supports them every step of the way. Classes are engaging and you’ll build personalized projects and applications in every lesson. 

No matter how you do it, we encourage you to keep practicing your Python!