Random Joke Generator Python- Complete Code Tutorial
What You're Building
A Python script that spits out random jokes on command. That's it. No GUI, no database, no unnecessary complexity. Just working code you can run in seconds.
I'll show you three approaches: the quick-and-dirty list method, the API method for real jokes, and a command-line tool you can actually use daily.
Prerequisites
- Python 3.6 or newer installed
- Basic understanding of variables and functions
- A terminal or command prompt
If you don't have Python, download it here. Takes 2 minutes.
Method 1: The List Method (Fastest)
This approach stores jokes in a Python list. No internet required. Works offline. Limitations: limited variety.
import random
jokes = [
"Why don't scientists trust atoms? Because they make up everything.",
"Why did the scarecrow win an award? He was outstanding in his field.",
"Why don't eggs tell jokes? They'd crack each other up.",
"What do you call a fake noodle? An impasta.",
"Why did the bicycle fall over? Because it was two tired.",
]
def tell_joke():
return random.choice(jokes)
print(tell_joke())
Run it. You'll get a random joke every time. That's the whole thing.
Adding Categories
Want to organize jokes by type? Use a dictionary:
import random
jokes = {
"tech": [
"Why do Java developers wear glasses? They can't C#.",
"How many programmers does it take to change a light bulb? None—that's a hardware problem.",
],
"dad": [
"I'm reading a book about anti-gravity. Can't put it down.",
"I used to hate facial hair... but then it grew on me.",
],
"clean": [
"Why did the student eat his homework? Because his teacher told him it was a piece of cake.",
],
}
def tell_joke(category=None):
if category:
return random.choice(jokes.get(category, jokes["clean"]))
return random.choice(random.choice(list(jokes.values())))
print(tell_joke("tech"))
Method 2: Using an API (Real Jokes)
The list method gets old fast. Here's how to pull jokes from the internet using the Official Joke API—it's free, no API key needed.
import requests
import random
def get_random_joke():
response = requests.get("https://official-joke-api.appspot.com/random_joke")
if response.status_code == 200:
data = response.json()
return f"{data['setup']} ... {data['punchline']}"
return "Failed to fetch joke. Check your internet."
print(get_random_joke())
Install requests first:
pip install requests
Output looks like this:
Why did the developer go broke? ... Because he used up all his cache.
Getting Multiple Jokes
import requests
import random
def get_jokes(count=5):
response = requests.get(f"https://official-joke-api.appspot.com/jokes/ten")
if response.status_code == 200:
jokes = response.json()
return [(joke['setup'], joke['punchline']) for joke in jokes[:count]]
return []
for setup, punchline in get_jokes(3):
print(f"{setup}")
print(f" → {punchline}\n")
Method 3: Command-Line Tool
Turn your joke generator into a CLI tool you can call from anywhere:
#!/usr/bin/env python3
import sys
import requests
import random
JOKES = [
"Why do Python developers prefer snakes? Because they hate semicolons.",
"What's a programmer's favorite hangout place? The Foo Bar.",
"Why was the JavaScript developer sad? Because he didn't Node how to Express himself.",
]
def local_joke():
return random.choice(JOKES)
def api_joke():
try:
r = requests.get("https://official-joke-api.appspot.com/random_joke", timeout=5)
data = r.json()
return f"{data['setup']} ... {data['punchline']}"
except:
return "API failed. Here's a local one: " + local_joke()
if __name__ == "__main__":
if "--local" in sys.argv:
print(local_joke())
else:
print(api_joke())
Save as joke.py, make it executable:
chmod +x joke.py
Run it:
python joke.py
python joke.py --local
Comparing the Three Methods
| Method | Speed | Variety | Internet Required | Best For |
|---|---|---|---|---|
| List Method | Instant | Limited | No | Offline use, quick demos |
| API Method | 1-2 seconds | Unlimited | Yes | Real jokes, variety |
| CLI Tool | Varies | Both options | Optional | Daily use, scripts |
How to Get Started Right Now
Follow these steps. Takes less than 5 minutes.
Step 1: Create Your Project Folder
mkdir joke-generator
cd joke-generator
Step 2: Create the Script
Open a text editor. Paste this complete working version:
#!/usr/bin/env python3
import random
import requests
# Local backup jokes
LOCAL_JOKES = [
"Why do programmers prefer iOS development? Because they can't handle the Java.",
"There are 10 types of people: those who understand binary and those who don't.",
"A SQL query walks into a bar, walks up to two tables and asks: 'Can I join you?'",
]
def tell_joke():
"""Try API first, fall back to local jokes."""
try:
response = requests.get(
"https://official-joke-api.appspot.com/random_joke",
timeout=3
)
if response.status_code == 200:
data = response.json()
print(data['setup'])
print(f"\n{data['punchline']}")
return
except:
pass
# Fallback
joke = random.choice(LOCAL_JOKES)
print(joke)
if __name__ == "__main__":
print("\n🎭 Random Joke Generator\n" + "=" * 25)
tell_joke()
print("=" * 25)
Step 3: Save and Run
python joke_generator.py
Expected output:
🎭 Random Joke Generator
========================
Why do programmers always mix up Halloween and Christmas?
Because Oct 31 equals Dec 25.
========================
Step 4: Install Requests (If Needed)
pip install requests
Done. That's your working joke generator.
Common Problems
ImportError: No module named 'requests'
Run pip install requests. That's it.
API returns nothing
Check your internet connection. The API might be down—use the local fallback.
Unicode emojis not displaying
On Windows? Use PowerShell or Windows Terminal instead of cmd.exe.
Permission denied on Linux/Mac
Run chmod +x joke_generator.py before executing.
What You Can Add Next
- Save jokes to a file so they don't repeat
- Add a --count flag to show multiple jokes
- Build a Tkinter GUI for fun
- Add more joke APIs for variety
- Create a Telegram bot that sends jokes daily
These are optional. The code above works fine as-is.
The Bottom Line
You have working code. Three different approaches. Copy what fits your needs, ignore the rest. No ceremony required.