Python - Create an Interactive Quote Generator



Here, we will create a Python script that retrieve quotes from an API, deal with errors and present textual quotes based on the particular inputs that are provided by the user.

Installations

First, we have to install to the requests module.

We can easily install it using pip. Go to terminal use this code −

pip install requests

Solution Explanation

The below given Python code explain how to read random quotes from an API and asks to user to select the quotes according to the mood they are in.

The script is structured into two main functions and error handling −

1. get_random_quote() Method

With this method, the application makes an HTTP GET request to the Quotable API which is now https://api. quotable. io/random. It handles errors that may occur when carrying out the request, and network issues that may interfere with the processing of the request or receipt of improper responses, to check that if there are any errors they should be caught and their details provided.

2. Error Handling

This is being done by the use of an exception handling tool known as the try except block which manages the requests. exceptions. Although the function is heavily commented I have deliberately put it into RequestException to guarantee that even in case of network errors the script looks strong.

3. main()

They accept inputs from the user and guides the process based on the instructions given by the user. It will inquire the user whether he or she is happy or sad and then the program will go to a loop where the user can ask for quotes or the program to terminate. This loop has an intention of scanning the input of the user and also perform some other actions if required. User Interaction: This way the user can type ‘get’ to continue with another quote of the day or type ‘exit’ to bring the end of the script. This interactivity continues until the user has had enough of the system and can thereby gain a good feel of the system.

Python Code to Create an Interactive Quote Generator

import requests

def get_random_quote():
   url = "https://api.quotable.io/random"
   try:
      response = requests.get(url)
      response.raise_for_status()  # Raise an exception for HTTP errors
      quote_data = response.json()
      return f"{quote_data['content']} - {quote_data['author']}"
   except requests.exceptions.RequestException as e:
      return f"Error fetching quote: {e}"

def main():
   expression = input("Enter expression (happy/sad): ").strip().lower()
   if expression not in ['happy', 'sad']:
      print("Invalid expression. Please choose 'happy' or 'sad'.")
      return

   print(f"Quotes for {expression} mood:")
   while True:
      user_input = input("Type 'get' for a quote or 'exit' to stop: ").strip().lower()
      if user_input == 'get':
         print(get_random_quote())
      elif user_input == 'exit':
         print("Exiting the program.")
         break
      else:
         print("Invalid input. Please type 'get' or 'exit'.")

if __name__ == "__main__":
   main()

Output

Quote Generator

There are two expression happy and Sad, this is for sad expression output.

Quote Generator

This is for happy expression output.

Code Summary

This code will show two expressions: happy and sad. If you select that means you have to write happy and sad. After you write happy, it will show what you want to get or exit. If you write get, it will give you a random quote, and it will also show the author name. After that, it will again show the get or exit menu. If you write exit, it will exit from the code.

Conclusion

The means to invoke data from an online API and also to respond to user-input, in an automated process is an essential quality in todays programming environment. Apart from presenting practical application of the requests library this Python script demonstrates the issues of error handling and user interaction as some of the most crucial aspects of development. Thus, by adopting this approach, the developers will be able to create engaging applications that offer data in real-time.

python_projects_from_basic_to_advanced.htm
Advertisements