Skip to content
Related Articles

Related Articles

Find jokes on a user provided topics using Python
  • Last Updated : 24 Jan, 2021

Prerequisites :

Python requests module helps us make Http requests to specified URL. In this article we will make a json request to this url:  https://icanhazdadjoke.com/ and develop a project wherein the user enters any word and the output would be a joke related to that word. 

We will be using API (library request) to search jokes using a keyword entered by the user if we get multiple results on the keyword entered then one of those jokes will be displayed randomly.

Modules Used

  • requests module allows us to sent the Https requests using python
  • pyfiglet module converts the ASCII texts to ASCII art fonts
  • termcolor module helps us format color in the output terminal
  • random module generates random numbers numbers in Python

Approach

  • Import module
  • Add header, to specify in for, is data to be stored, by default it is html text(Here, we are getting data in JSON format)
  • Ask user for input
  • Pass input as searching element to retrieve data from URL
  • Print retrieved data.

Program:

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

import requests
import pyfiglet
import termcolor
from random import choice
  
header = pyfiglet.figlet_format("Find a joke!")
header = termcolor.colored(header, color="white")
print(header)
  
term = input("Let me tell you a joke! Give me a topic: ")
  
response_json = requests.get("https://icanhazdadjoke.com/search",
                             headers={"Accept": "application/json"}, params={"term": term}).json()
  
results = response_json["results"]
  
total_jokes = response_json["total_jokes"]
print(total_jokes)
  
if total_jokes > 1:
    print(f"I've got {total_jokes} jokes about {term}. Here's one:\n", choice(
        results)['joke'])
  
elif total_jokes == 1:
    print(f"I've got one joke about {term}. Here it is:\n", results[0]['joke'])
  
else:
    print(f"Sorry, I don't have any jokes about {term}! Please try again.")

chevron_right


Output

The keyword passes was banana, one of the joke related to is displayed


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :