Introduction
In this tutorial, we will create a simple Python program that displays a random quote from a list of quotes. This program allows us to practice handling lists and generating random values in Python.
Objective
The objective of this program is to generate and display a random quote from a predefined list. It helps in understanding how to use Python’s random module and basic list operations.
Python Code
import random # List of quotes quotes = [ "The only way to do great work is to love what you do. - Steve Jobs", "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill", "Believe you can and you're halfway there. - Theodore Roosevelt", "It does not matter how slowly you go as long as you do not stop. - Confucius", "The best time to plant a tree was 20 years ago. The second best time is now. - Chinese Proverb" ] # Function to display a random quote def display_random_quote(): # Select a random quote from the list quote = random.choice(quotes) print("Random Quote: " + quote) # Call the function to display a random quote display_random_quote()
Explanation of the Program
This Python program works as follows:
- Step 1: We first define a list of quotes that we want to choose from.
- Step 2: The
random.choice()
function is used to randomly select an item from the list of quotes. - Step 3: The selected quote is then printed to the console by the
print()
function. - Step 4: The
display_random_quote()
function is called to initiate the process.
How to Run the Program
Follow these steps to run the program:
- Open a text editor (like Notepad, VS Code, or PyCharm) and copy the Python code provided.
- Save the file with a
.py
extension (for example,random_quote.py
). - Open the command line or terminal on your computer.
- Navigate to the directory where the Python file is saved.
- Run the program by typing
python random_quote.py
and pressing Enter. - The program will display a random quote from the list in the console.