60 Python Programs for Beginners to Advanced
19 mins read

60 Python Programs for Beginners to Advanced

A Collection of 60 Python Programs for Practice and Learning

1. Hello World Program

# Hello World Program

# This is a simple Python program that prints "Hello, World!" to the console.
print("Hello, World!")

Explanation:

  • # Hello World Program: This line is a comment. Comments are not executed as code but provide information about the code to programmers. In this case, it’s just a description of what the program does.
  • print("Hello, World!"): This line is responsible for printing the text “Hello, World!” to the console. The print function is used to display output to the screen, and in this case, it’s printing the specified string.

Output:

Hello, World!

This program is the simplest Python program and serves as an introduction to Python syntax.


2. Calculator (Addition, Subtraction, Multiplication, Division)

# Calculator Program

# Input two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform addition, subtraction, multiplication, and division
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2

# Display the results
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)

Explanation:

  • # Calculator Program: This is a comment describing the purpose of the program.
  • num1 = float(input("Enter first number: ")) and num2 = float(input("Enter second number: ")): These lines prompt the user to enter two numbers and store them as floating-point (decimal) values in the variables num1 and num2.
  • addition = num1 + num2, subtraction = num1 - num2, multiplication = num1 * num2, and division = num1 / num2: These lines perform addition, subtraction, multiplication, and division operations on the entered numbers and store the results in corresponding variables.
  • print("Addition:", addition), print("Subtraction:", subtraction), print("Multiplication:", multiplication), and print("Division:", division): These lines display the results of the calculations to the console.

Output:

Enter first number: 5
Enter second number: 3
Addition: 8.0
Subtraction: 2.0
Multiplication: 15.0
Division: 1.6666666666666667

This program takes two numbers as input, performs basic arithmetic operations, and displays the results.


3. Simple Interest Calculator

# Simple Interest Calculator

# Input principal amount, rate of interest, and time period from the user
principal = float(input("Enter principal amount: "))
rate_of_interest = float(input("Enter rate of interest (% per annum): "))
time_period = float(input("Enter time period (in years): "))

# Calculate simple interest
simple_interest = (principal * rate_of_interest * time_period) / 100

# Display the calculated simple interest
print("Simple Interest:", simple_interest)

Explanation:

  • # Simple Interest Calculator: This is a comment describing the purpose of the program.
  • principal = float(input("Enter principal amount: ")), rate_of_interest = float(input("Enter rate of interest (% per annum): ")), and time_period = float(input("Enter time period (in years): ")): These lines prompt the user to enter the principal amount, rate of interest (as a percentage per annum), and time period (in years) and store them as floating-point values in the respective variables.
  • simple_interest = (principal * rate_of_interest * time_period) / 100: This line calculates the simple interest using the formula Simple Interest = (Principal * Rate * Time) / 100.
  • print("Simple Interest:", simple_interest): This line displays the calculated simple interest to the console.

Output (example):

Enter principal amount: 1000
Enter rate of interest (% per annum): 5
Enter time period (in years): 3
Simple Interest: 150.0

This program calculates and displays the simple interest based on user-provided inputs.


4. Area of a Rectangle

# Area of a Rectangle Calculator

# Input length and width of the rectangle from the user
length = float(input("Enter length of the rectangle: "))
width = float(input("Enter width of the rectangle: "))

# Calculate the area of the rectangle
area = length * width

# Display the calculated area
print("Area of the rectangle:", area)

Explanation:

  • # Area of a Rectangle Calculator: This is a comment describing the purpose of the program.
  • length = float(input("Enter length of the rectangle: ")) and width = float(input("Enter width of the rectangle: ")): These lines prompt the user to enter the length and width of the rectangle and store them as floating-point values in the variables length and width.
  • area = length * width: This line calculates the area of the rectangle using the formula Area = Length * Width.
  • print("Area of the rectangle:", area): This line displays the calculated area of the rectangle to the console.

Output (example):

Enter length of the rectangle: 6
Enter width of the rectangle: 4
Area of the rectangle: 24.0

This program calculates and displays the area of a rectangle based on user-provided inputs.


5. Area of a Triangle

# Area of a Triangle Calculator

# Input base and height of the triangle from the user
base = float(input("Enter base length of the triangle: "))
height = float(input("Enter height of the triangle: "))

# Calculate the area of the triangle
area = 0.5 * base * height

# Display the calculated area
print("Area of the triangle:", area)

Explanation:

  • # Area of a Triangle Calculator: This is a comment describing the purpose of the program.
  • base = float(input("Enter base length of the triangle: ")) and height = float(input("Enter height of the triangle: ")): These lines prompt the user to enter the base length and height of the triangle and store them as floating-point values in the variables base and height.
  • area = 0.5 * base * height: This line calculates the area of the triangle using the formula Area = 0.5 * Base * Height, which is half the product of the base and height.
  • print("Area of the triangle:", area): This line displays the calculated area of the triangle to the console.

Output (example):

Enter base length of the triangle: 8
Enter height of the triangle: 5
Area of the triangle: 20.0

Sure, I’ll provide Python programs and explanations for each of the requested topics.


6. Area of a Circle

import math

# Input the radius of the circle
radius = float(input("Enter the radius of the circle: "))

# Calculate the area of the circle
area = math.pi * (radius ** 2)

# Display the result
print(f"The area of the circle with radius {radius} is {area:.2f} square units.")

Explanation:

  1. We start by importing the math module to access the value of π (pi), which is necessary for the area calculation.
  2. We prompt the user to enter the radius of the circle using input(), and we convert the input to a floating-point number using float().
  3. The area of a circle is calculated using the formula: π * r^2, where π is pi, and r is the radius. We calculate the area and store it in the area variable.
  4. Finally, we display the result using print(). We use an f-string (formatted string) to include the radius and the calculated area with two decimal places.

Output:

Let’s say the user enters a radius of 5 units.

Enter the radius of the circle: 5
The area of the circle with radius 5.0 is 78.54 square units.

7. Celsius to Fahrenheit Converter

# Input temperature in Celsius
celsius = float(input("Enter temperature in Celsius: "))

# Convert Celsius to Fahrenheit
fahrenheit = (celsius * 9/5) + 32

# Display the result
print(f"{celsius} degrees Celsius is equal to {fahrenheit:.2f} degrees Fahrenheit.")

Explanation:

  1. We prompt the user to enter a temperature in Celsius using input(), and we convert the input to a floating-point number using float().
  2. We use the formula to convert Celsius to Fahrenheit: F = (C × 9/5) + 32, where F is Fahrenheit and C is Celsius.
  3. The converted temperature is stored in the fahrenheit variable.
  4. We display the result using print() with an f-string to show the original temperature in Celsius and the converted temperature in Fahrenheit with two decimal places.

Output:

If the user enters 25 degrees Celsius:

Enter temperature in Celsius: 25
25.0 degrees Celsius is equal to 77.00 degrees Fahrenheit.

8. Fahrenheit to Celsius Converter

# Input temperature in Fahrenheit
fahrenheit = float(input("Enter temperature in Fahrenheit: "))

# Convert Fahrenheit to Celsius
celsius = (fahrenheit - 32) * 5/9

# Display the result
print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius:.2f} degrees Celsius.")

Explanation:

  1. We prompt the user to enter a temperature in Fahrenheit using input(), and we convert the input to a floating-point number using float().
  2. We use the formula to convert Fahrenheit to Celsius: C = (F - 32) × 5/9, where C is Celsius and F is Fahrenheit.
  3. The converted temperature is stored in the celsius variable.
  4. We display the result using print() with an f-string to show the original temperature in Fahrenheit and the converted temperature in Celsius with two decimal places.

Output:

If the user enters 98.6 degrees Fahrenheit:

Enter temperature in Fahrenheit: 98.6
98.6 degrees Fahrenheit is equal to 37.00 degrees Celsius.

9. Guess the Number Game

import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Initialize the number of attempts
attempts = 0

print("Welcome to the Guess the Number Game!")
print("I'm thinking of a number between 1 and 100. Try to guess it.")

while True:
    # Get the user's guess
    guess = int(input("Enter your guess: "))

    # Increment the number of attempts
    attempts += 1

    # Check if the guess is correct
    if guess == secret_number:
        print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts.")
        break
    elif guess < secret_number:
        print("Try a higher number.")
    else:
        print("Try a lower number.")

Explanation:

  1. We import the random module to generate a random number for the player to guess.
  2. We generate a random integer between 1 and 100 using random.randint(1, 100) and store it in secret_number.
  3. We initialize the attempts variable to keep track of how many attempts the player has made.
  4. We provide a welcome message and instructions to the player.
  5. We enter a while loop that continues until the player correctly guesses the number.
  6. Inside the loop, we ask the player to enter their guess using input(), and we convert the input to an integer.
  7. We increment the attempts variable for each guess.
  8. We check if the guess is correct. If it is, we print a congratulatory message and display the number of attempts it took to guess correctly. We then break out of the loop.
  9. If the guess is not correct, we provide a hint to the player, either to try a higher or lower number.

Output:

The program will keep running until the player guesses the correct number. Here’s an example of how it might look:

Welcome to the Guess the Number Game!
I'm thinking of a number between 1 and 100. Try to guess it.
Enter your guess: 50
Try a higher number.
Enter your guess: 75
Try a higher number.
Enter your guess: 85
Try a lower number.
Enter your guess: 80
Congratulations! You guessed the number 80 in 4 attempts.

10. Rock, Paper, Scissors Game

import random

# Define the choices
choices = ["rock", "paper", "scissors"]

# Get the user's choice
user_choice = input("Choose rock, paper, or scissors: ").lower()

# Validate the user's choice
if user_choice not in choices:
    print("Invalid choice. Please choose rock, paper, or scissors.")
else:
    # Randomly select the computer's choice
    computer_choice = random.choice(choices)

    # Display the choices
    print(f"Your choice: {user_choice}")
    print(f"Computer's choice: {computer_choice}")

    # Determine the winner
    if user_choice == computer_choice:
        print("It's a tie!")
    elif (user_choice == "rock" and computer_choice == "scissors") or \
         (user_choice == "paper" and computer_choice == "rock") or \
         (user_choice == "scissors" and computer_choice == "paper"):
        print("You win!")
    else:
        print("Computer wins!")

**

Explanation:**

  1. We define the possible choices for the game: “rock,” “paper,” and “scissors.”
  2. We ask the user to input their choice using input(), and we convert the input to lowercase using .lower() to make it case-insensitive.
  3. We validate the user’s choice to ensure it’s one of the valid options. If not, we inform the user to choose from the available options.
  4. If the user’s choice is valid, we randomly select the computer’s choice using random.choice(choices).
  5. We display both the user’s and the computer’s choices.
  6. We determine the winner based on the game rules: rock beats scissors, scissors beats paper, and paper beats rock.

Output:

The program will show the user’s and computer’s choices and announce the winner. Here’s an example:

Choose rock, paper, or scissors: Rock
Your choice: rock
Computer's choice: scissors
You win!

In this example, the user chose “rock,” and the computer chose “scissors,” so the user wins.

Certainly, I’ll provide Python programs and explanations for each of the requested topics.


11. Basic Calculator with GUI

import tkinter as tk

# Create a function to perform calculations
def calculate():
    try:
        num1 = float(entry_num1.get())
        num2 = float(entry_num2.get())
        operator = operator_var.get()

        if operator == "+":
            result = num1 + num2
        elif operator == "-":
            result = num1 - num2
        elif operator == "*":
            result = num1 * num2
        elif operator == "/":
            if num2 == 0:
                result = "Division by zero"
            else:
                result = num1 / num2
        result_label.config(text=f"Result: {result}")
    except ValueError:
        result_label.config(text="Invalid input")

# Create the main GUI window
window = tk.Tk()
window.title("Basic Calculator")

# Create input fields
entry_num1 = tk.Entry(window)
entry_num2 = tk.Entry(window)

# Create an operator selection
operator_var = tk.StringVar()
operator_var.set("+")  # Default operator
operator_dropdown = tk.OptionMenu(window, operator_var, "+", "-", "*", "/")

# Create a Calculate button
calculate_button = tk.Button(window, text="Calculate", command=calculate)

# Create a label to display the result
result_label = tk.Label(window, text="Result:")

# Organize the widgets
entry_num1.pack()
operator_dropdown.pack()
entry_num2.pack()
calculate_button.pack()
result_label.pack()

# Start the GUI event loop
window.mainloop()

Explanation:

  1. We import the tkinter library to create a graphical user interface (GUI).
  2. We define a calculate function that retrieves the user’s input from entry fields, performs the calculation based on the selected operator, and displays the result or error message.
  3. We create the main GUI window using tk.Tk() and set its title.
  4. Entry fields are created for the user to input numbers (entry_num1 and entry_num2).
  5. We create an operator selection dropdown (operator_dropdown) using the OptionMenu widget.
  6. A “Calculate” button (calculate_button) is created, and we associate it with the calculate function.
  7. We create a label (result_label) to display the result.
  8. We organize and display the widgets using pack().
  9. Finally, we start the GUI event loop with window.mainloop().

Output:

This program opens a GUI window where you can enter two numbers, select an operator, and click the “Calculate” button to perform calculations.


12. Check if a Number is Even or Odd

# Input a number from the user
num = int(input("Enter a number: "))

# Check if the number is even or odd
if num % 2 == 0:
    print(f"{num} is even.")
else:
    print(f"{num} is odd.")

Explanation:

  1. We ask the user to input a number using input() and convert it to an integer using int().
  2. We check if the number is even or odd using the modulo operator %. If the remainder when dividing by 2 is 0, it’s even; otherwise, it’s odd.
  3. We print the result based on the condition.

Output:

If the user enters the number 7:

Enter a number: 7
7 is odd.

13. Sum of N Natural Numbers

# Input a positive integer from the user
n = int(input("Enter a positive integer: "))

# Initialize the sum
sum_of_numbers = 0

# Calculate the sum of natural numbers from 1 to n
for i in range(1, n + 1):
    sum_of_numbers += i

# Display the result
print(f"The sum of natural numbers from 1 to {n} is {sum_of_numbers}.")

Explanation:

  1. We ask the user to input a positive integer using input() and convert it to an integer using int().
  2. We initialize a variable sum_of_numbers to store the sum.
  3. We use a for loop to iterate from 1 to n (inclusive) and add each number to sum_of_numbers.
  4. Finally, we print the sum of natural numbers from 1 to n.

Output:

If the user enters 5:

Enter a positive integer: 5
The sum of natural numbers from 1 to 5 is 15.

14. Factorial of a Number

# Input a non-negative integer from the user
num = int(input("Enter a non-negative integer: "))

# Initialize the factorial
factorial = 1

# Calculate the factorial of the number
if num < 0:
    print("Factorial is undefined for negative numbers.")
elif num == 0:
    print("The factorial of 0 is 1.")
else:
    for i in range(1, num + 1):
        factorial *= i
    print(f"The factorial of {num} is {factorial}.")

Explanation:

  1. We ask the user to input a non-negative integer using input() and convert it to an integer using int().
  2. We initialize a variable factorial to store the factorial value.
  3. We check if the input number is negative, zero, or positive using if, elif, and else.
  4. If the number is negative, we inform the user that the factorial is undefined for negative numbers.
  5. If the number is zero, we inform the user that the factorial of 0 is 1.
  6. If the number is positive, we use a for loop to calculate the factorial by multiplying each number from 1 to num.
  7. Finally, we print the factorial of the input number.

Output:

If the user enters 5:

Enter a non-negative integer: 5
The factorial of 5 is 120.

15. Fibonacci Series

# Input the number of terms in the Fibonacci series
n = int(input("Enter the number of terms in the Fibonacci series: "))

# Initialize the first two terms
a, b = 0, 1

# Initialize a list to store the Fibonacci series
fibonacci_series = []

# Generate the Fibonacci series
for i in range(n):
    fibonacci_series.append(a)
    a, b = b, a + b

# Display the Fibonacci series
print(f"The first {n} terms of the Fibonacci series are:")
print(fibonacci_series)

Explanation:

  1. We ask the user to input the number of terms they want in the Fibonacci series using input() and convert it to an integer using int().
  2. We initialize the first two terms of the series, a and b, to 0 and 1, respectively.
  3. We initialize an empty list, fibonacci_series, to store the Fibonacci series.
  4. Using a for loop, we generate the Fibonacci series by appending the current term (`a

) to the list, then updatingaandb` to calculate the next term in the series.

  1. Finally, we display the generated Fibonacci series.

Output:

If the user enters 10:

Enter the number of terms in the Fibonacci series: 10
The first 10 terms of the Fibonacci series are:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

This program generates and displays the first 10 terms of the Fibonacci series.


16. Prime Number Checker

# Input a positive integer from the user
num = int(input("Enter a positive integer: "))

# Check if the number is prime
if num <= 1:
    print(f"{num} is not a prime number.")
else:
    is_prime = True
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(f"{num} is a prime number.")
    else:
        print(f"{num} is not a prime number.")

Explanation:

  1. We ask the user to input a positive integer using input() and convert it to an integer using int().
  2. We check if the input number is less than or equal to 1. If so, it’s not a prime number, and we print the result.
  3. If the number is greater than 1, we assume it’s prime (is_prime is initially True) and use a for loop to check for factors from 2 to the square root of the number.
  4. If we find any factor, we set is_prime to False and break out of the loop.
  5. Finally, we print whether the number is prime or not based on the value of is_prime.

Output:

If the user enters 17:

Enter a positive integer: 17
17 is a prime number.

17. Reverse a String

# Input a string from the user
input_string = input("Enter a string: ")

# Reverse the string
reversed_string = input_string[::-1]

# Display the reversed string
print(f"The reversed string is: {reversed_string}")

Explanation:

  1. We ask the user to input a string using input().
  2. We reverse the string using slicing with [::-1], which reverses the string.
  3. We display the reversed string.

Output:

If the user enters “Hello”:

Enter a string: Hello
The reversed string is: olleH

18. Check for Palindrome

# Input a string from the user
input_string = input("Enter a string: ")

# Remove spaces and convert to lowercase
cleaned_string = input_string.replace(" ", "").lower()

# Check if the cleaned string is a palindrome
if cleaned_string == cleaned_string[::-1]:
    print(f"{input_string} is a palindrome.")
else:
    print(f"{input_string} is not a palindrome.")

Explanation:

  1. We ask the user to input a string using input().
  2. We clean the input string by removing spaces and converting it to lowercase.
  3. We check if the cleaned string is a palindrome by comparing it to its reverse.
  4. We print whether the original string is a palindrome or not.

Output:

If the user enters “A man a plan a canal Panama”:

Enter a string: A man a plan a canal Panama
A man a plan a canal Panama is a palindrome.

19. Find the Largest Number in a List

# Input a list of numbers from the user
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]

# Find the largest number
if not numbers:
    print("The list is empty.")
else:
    largest_number = max(numbers)
    print(f"The largest number in the list is: {largest_number}")

Explanation:

  1. We ask the user to input a list of numbers separated by spaces using input(). We split the input string into a list of floats.
  2. We check if the list is empty. If it is, we inform the user.
  3. If the list is not empty, we use the max() function to find the largest number.
  4. We print the largest number in the list.

Output:

If the user enters “3.14 2.71 1.618”:

Enter a list of numbers separated by spaces: 3.14 2.71 1.618
The largest number in the list is: 3.14

20. Count Vowels and Consonants in a String

# Input a string from the user
input_string = input("Enter a string: ")

# Convert the string to lowercase
input_string = input_string.lower()

# Initialize counters for vowels and consonants
vowels = 0
consonants = 0

# Define the set of vowels
vowel_set = set("aeiou")

# Count vowels and consonants
for char in input_string:
    if char.isalpha():
        if char in vowel_set:
            vowels += 1
        else:
            consonants += 1

# Display the counts
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")

Explanation:

  1. We ask the user to input a string using input().
  2. We convert the string to lowercase to make the counting case-insensitive.
  3. We initialize counters for vowels and consonants.
  4. We define a set of vowels for efficient vowel checking.
  5. Using a for loop, we iterate through each character in the string, check if it’s an alphabet character using char.isalpha(), and increment the respective counter based on whether it’s a vowel or consonant.
  6. Finally, we display the counts of vowels and consonants.

Output:

If the user enters “Hello World”:

Enter a string: Hello World
Vowels: 3
Consonants: 7

21. Basic File Handling (Read/Write to a Text File)

Write to a File:

# Open a file in write mode
with open("sample.txt", "w") as file:
    file.write("Hello, world!\n")
    file.write("This is a sample text file.\n")
    file.write("Python is awesome!\n")

Explanation:

  1. We open a file named “sample.txt” in write mode using the open() function with the “w” mode.
  2. We use the with statement to ensure the file is properly closed when we’re done with it.
  3. We write three lines of text to the file using the file.write() method. The “\n” character is used to indicate a new line.

Read from a File:

# Open the same file in read mode
with open("sample.txt", "r") as file:
    contents = file.read()
    print(contents)

Explanation:

  1. We open the same file, “sample.txt,” but this time in read mode (“r”).
  2. We use the with statement to ensure the file is properly closed.
  3. We read the entire contents of the file into a string using file.read().
  4. We print the contents of the file to the console.

Output:

If the file “sample

.txt” contains the following text:

Hello, world!
This is a sample text file.
Python is awesome!

The output of the read operation will be:

Hello, world!
This is a sample text file.
Python is awesome!

22. Basic Exception Handling (Try-Except)

try:
    # Attempt to perform a risky operation
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Division by zero is not allowed.")
except ValueError:
    print("Invalid input. Please enter a valid number.")
except Exception as e:
    print(f"An error occurred: {e}")

Explanation:

  1. We use a try block to enclose code that might raise exceptions.
  2. Inside the try block, we attempt to perform a risky operation: dividing 10 by a user-input number.
  3. We use int(input()) to get a number from the user, which might raise a ValueError if the input is not a valid integer.
  4. We handle specific exceptions using except blocks. In this example, we handle ZeroDivisionError if the user inputs 0, ValueError for invalid input, and a generic Exception for any other unexpected errors.
  5. If an exception is caught, the corresponding error message is displayed. If no exceptions occur, the result is displayed.

Output:

If the user enters 2:

Enter a number: 2
Result: 5.0

If the user enters 0:

Enter a number: 0
Division by zero is not allowed.

If the user enters “abc”:

Enter a number: abc
Invalid input. Please enter a valid number.

23. Simple Stopwatch

import time

# Start the stopwatch
start_time = time.time()

# Wait for user input to stop the stopwatch
input("Press Enter to stop the stopwatch...")

# Stop the stopwatch
end_time = time.time()

# Calculate and display the elapsed time
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds")

Explanation:

  1. We import the time module to work with time-related functions.
  2. We start the stopwatch by recording the current time using time.time() and store it in start_time.
  3. We wait for user input (pressing Enter) to stop the stopwatch using input().
  4. After the user presses Enter, we record the current time again using time.time() and store it in end_time.
  5. We calculate the elapsed time by subtracting start_time from end_time.
  6. We display the elapsed time with two decimal places.

Output:

When the user presses Enter to stop the stopwatch, the program will display the elapsed time, which will vary depending on how long the user waits.

For example:

Press Enter to stop the stopwatch...
Elapsed time: 5.72 seconds

24. Generate Random Numbers

import random

# Generate a random integer between 1 and 10
random_int = random.randint(1, 10)

# Generate a random floating-point number between 0 and 1
random_float = random.random()

# Display the generated numbers
print(f"Random integer: {random_int}")
print(f"Random float: {random_float:.2f}")

Explanation:

  1. We import the random module to generate random numbers.
  2. We use random.randint(1, 10) to generate a random integer between 1 and 10 (inclusive) and store it in random_int.
  3. We use random.random() to generate a random floating-point number between 0 and 1 and store it in random_float.
  4. We display the generated random integer and random float.

Output:

The generated numbers will vary each time you run the program. Here’s an example of the output:

Random integer: 7
Random float: 0.85

25. Simple Todo List Application

# Initialize an empty list to store tasks
todo_list = []

while True:
    # Display the menu
    print("\nTodo List Menu:")
    print("1. Add Task")
    print("2. View Tasks")
    print("3. Mark Task as Done")
    print("4. Quit")

    # Get user choice
    choice = input("Enter your choice: ")

    if choice == "1":
        # Add a task
        task = input("Enter a task: ")
        todo_list.append({"task": task, "done": False})
        print("Task added.")

    elif choice == "2":
        # View tasks
        print("\n

Tasks:")
        for i, item in enumerate(todo_list, 1):
            status = "Done" if item["done"] else "Not Done"
            print(f"{i}. {item['task']} ({status})")

    elif choice == "3":
        # Mark task as done
        task_number = int(input("Enter the task number to mark as done: "))
        if 1 <= task_number <= len(todo_list):
            todo_list[task_number - 1]["done"] = True
            print("Task marked as done.")
        else:
            print("Invalid task number.")

    elif choice == "4":
        # Quit the program
        print("Goodbye!")
        break

    else:
        print("Invalid choice. Please select a valid option.")

Explanation:

  1. We initialize an empty list called todo_list to store tasks. Each task is represented as a dictionary with keys “task” (the task description) and “done” (a boolean indicating whether the task is done).
  2. We enter a while loop that displays a menu of options to the user and continues until the user chooses to quit.
  3. The menu has four options:
  • “1. Add Task” allows the user to input a task description and adds it to the todo_list.
  • “2. View Tasks” displays the tasks along with their status (done or not done).
  • “3. Mark Task as Done” allows the user to mark a task as done by entering its number.
  • “4. Quit” exits the program.
  1. The user’s choice is obtained using input().
  2. Depending on the user’s choice, the program performs the corresponding task, such as adding a task, displaying tasks, marking a task as done, or quitting the program.

Output:

The program provides a menu for adding, viewing, and managing tasks. Here’s a sample interaction:

Todo List Menu:
1. Add Task
2. View Tasks
3. Mark Task as Done
4. Quit
Enter your choice: 1
Enter a task: Buy groceries
Task added.

Todo List Menu:
1. Add Task
2. View Tasks
3. Mark Task as Done
4. Quit
Enter your choice: 2

Tasks:
1. Buy groceries (Not Done)

Todo List Menu:
1. Add Task
2. View Tasks
3. Mark Task as Done
4. Quit
Enter your choice: 3
Enter the task number to mark as done: 1
Task marked as done.

Todo List Menu:
1. Add Task
2. View Tasks
3. Mark Task as Done
4. Quit
Enter your choice: 2

Tasks:
1. Buy groceries (Done)

Todo List Menu:
1. Add Task
2. View Tasks
3. Mark Task as Done
4. Quit
Enter your choice: 4
Goodbye!

This program allows users to manage their todo list by adding, viewing, and marking tasks as done.


Sure, let’s go through five Python programs one by one, along with their explanations and outputs.

26: Basic Web Scraping (e.g., Weather Information)

import requests
from bs4 import BeautifulSoup

# Define the URL of the website to scrape
url = 'https://www.weather.com/weather/today/l/USNY0996:1:US'

# Send an HTTP GET request to the URL
response = requests.get(url)

# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Parse the HTML content of the page
    soup = BeautifulSoup(response.text, 'html.parser')

    # Find and extract the weather information
    weather_data = soup.find(class_='CurrentConditions--tempValue--3KcTQ')
    temperature = weather_data.get_text()

    # Print the temperature
    print(f"Current temperature: {temperature}")
else:
    print("Failed to retrieve weather information")

Explanation:

  • We start by importing the necessary libraries, requests for making HTTP requests and BeautifulSoup for parsing HTML content.
  • We define the URL of the website we want to scrape. In this case, it’s a weather page.
  • We send an HTTP GET request to the URL using requests.get(url) and store the response in the response variable.
  • We check if the request was successful by verifying that the status code of the response is 200, which indicates success.
  • If the request was successful, we parse the HTML content of the page using BeautifulSoup and specify the parser as 'html.parser'.
  • We locate the HTML element that contains the current temperature using its class name and extract the temperature value.
  • Finally, we print the current temperature.

Output:

The program will output the current temperature in the specified location, like:

Current temperature: 72°F

27: Basic Database CRUD (Create, Read, Update, Delete) Operations

import sqlite3

# Create a SQLite database (or connect to an existing one)
conn = sqlite3.connect('my_database.db')

# Create a cursor object to interact with the database
cursor = conn.cursor()

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
                  (id INTEGER PRIMARY KEY,
                   name TEXT,
                   age INTEGER)''')

# Insert data into the table
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('Alice', 20))

# Commit the changes to the database
conn.commit()

# Read data from the table
cursor.execute("SELECT * FROM students")
data = cursor.fetchall()

# Print the data
for row in data:
    print(row)

# Update data in the table
cursor.execute("UPDATE students SET age = ? WHERE name = ?", (21, 'Alice'))
conn.commit()

# Delete data from the table
cursor.execute("DELETE FROM students WHERE name = ?", ('Alice',))
conn.commit()

# Close the database connection
conn.close()

Explanation:

  • We import the sqlite3 module to work with SQLite databases.
  • We create a SQLite database or connect to an existing one using sqlite3.connect('my_database.db').
  • We create a cursor object cursor to interact with the database.
  • We create a table named “students” with three columns: id, name, and age.
  • We insert data into the table for a student named Alice.
  • We commit the changes to the database.
  • We read data from the table using a SELECT query and print the results.
  • We update Alice’s age to 21 and commit the change.
  • We delete the record for Alice from the table and commit the change.
  • Finally, we close the database connection.

Output:

The program will output the following:

(1, 'Alice', 20)
(1, 'Alice', 21)

The first set of data shows Alice’s initial information, and the second set reflects the updated age. The final database is empty because we deleted the record for Alice.


28: Basic GUI for Drawing Shapes

This program requires a GUI library like Tkinter to create a graphical user interface for drawing shapes. Please install Tkinter if it’s not already installed on your system.

import tkinter as tk

# Create a canvas for drawing
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

# Function to draw a rectangle
def draw_rectangle():
    canvas.create_rectangle(50, 50, 150, 150, fill='blue')

# Function to draw an oval
def draw_oval():
    canvas.create_oval(200, 50, 300, 150, fill='red')

# Create buttons to trigger drawing functions
rectangle_button = tk.Button(root, text='Draw Rectangle', command=draw_rectangle)
rectangle_button.pack()

oval_button = tk.Button(root, text='Draw Oval', command=draw_oval)
oval_button.pack()

# Start the GUI main loop
root.mainloop()

Explanation:

  • We import the tkinter library for creating the GUI.
  • We create a root window and a canvas for drawing shapes.
  • We define two functions, draw_rectangle and draw_oval, which use the create_rectangle and create_oval methods of the canvas to draw shapes.
  • We create buttons that call these functions when clicked.
  • Finally, we start the Tkinter main loop using root.mainloop() to display the GUI and handle user interactions.

Output:

The program will display a window with two buttons: “Draw Rectangle” and “Draw Oval.” Clicking these buttons will draw the respective shapes (a blue rectangle and a red oval) on the canvas.


29: Basic GUI for a Simple Calculator

This program creates a simple calculator GUI using Tkinter.

import tkinter as tk

# Create a calculator function
def evaluate(event):
    result = eval(entry.get())
    result_label.config(text="Result: " + str(result))

# Create a Tkinter window
root = tk.Tk()
root.title("Simple Calculator")

# Create an entry field
entry = tk.Entry(root, width=20)
entry.pack()

# Create a button to calculate the result
calculate_button = tk.Button(root, text="Calculate", command=lambda: evaluate(None))
calculate_button.pack()

# Create a label to display the result
result_label = tk.Label(root, text="Result:")
result_label.pack()

# Start the GUI main loop
root.mainloop()

Explanation:

  • We import the tkinter library to create the GUI.
  • We define an evaluate function that calculates the result of the expression entered in the entry field when the “Calculate” button is pressed.
  • We create a Tkinter window with the title “Simple Calculator.”
  • We create an entry field where the user can input mathematical expressions.
  • We create a “Calculate” button that triggers the evaluate function when clicked.
  • We create a label to display the result.
  • Finally, we start the Tkinter main loop to display the GUI and handle user interactions.

Output:

The program will display a GUI window with an entry field, a “Calculate” button, and a label for displaying the result. Users can enter

mathematical expressions in the entry field and click the “Calculate” button to see the result displayed below the button.


30: Simple Snake Game

This program uses the Pygame library to create a simple Snake game. Please install Pygame if it’s not already installed on your system.

import pygame
import time
import random

# Initialize Pygame
pygame.init()

# Define screen dimensions
WIDTH, HEIGHT = 400, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))

# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

# Snake initial position and speed
snake_x, snake_y = WIDTH // 2, HEIGHT // 2
snake_speed = 15

# Initialize snake length and direction
snake_length = 1
snake_direction = "RIGHT"

# Define snake body
snake_body = [(snake_x, snake_y)]

# Define food position
food_x, food_y = random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10

# Initialize score
score = 0

# Game over flag
game_over = False

# Main game loop
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake_direction = "UP"
            if event.key == pygame.K_DOWN:
                snake_direction = "DOWN"
            if event.key == pygame.K_LEFT:
                snake_direction = "LEFT"
            if event.key == pygame.K_RIGHT:
                snake_direction = "RIGHT"

    if snake_direction == "UP":
        snake_y -= 10
    if snake_direction == "DOWN":
        snake_y += 10
    if snake_direction == "LEFT":
        snake_x -= 10
    if snake_direction == "RIGHT":
        snake_x += 10

    snake_head = (snake_x, snake_y)
    snake_body.append(snake_head)

    if snake_x == food_x and snake_y == food_y:
        score += 10
        food_x, food_y = random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10
    else:
        snake_body.pop(0)

    screen.fill(BLACK)

    for segment in snake_body:
        pygame.draw.rect(screen, GREEN, [segment[0], segment[1], 10, 10])

    pygame.draw.rect(screen, WHITE, [food_x, food_y, 10, 10])

    pygame.display.update()

    if snake_x >= WIDTH or snake_x < 0 or snake_y >= HEIGHT or snake_y < 0:
        game_over = True

    if snake_head in snake_body[:-1]:
        game_over = True

    time.sleep(1/snake_speed)

pygame.quit()
quit()

Explanation:

  • We import the pygame library for creating the game.
  • We initialize Pygame and define the screen dimensions.
  • We define colors (BLACK, WHITE, and GREEN) to use in the game.
  • We set the initial position and speed of the snake, as well as its length and direction.
  • We define the snake’s body as a list of coordinates and the initial position of the food.
  • We initialize the score and the game over flag.
  • In the main game loop, we handle events, including quitting the game and changing the snake’s direction using arrow keys.
  • We update the snake’s position based on its direction.
  • We handle collision with food, update the score, and randomly reposition the food.
  • We draw the snake and the food on the screen.
  • We check for game over conditions: snake hitting the screen boundaries or colliding with itself.
  • We update the display and control the game speed.
  • Finally, we quit Pygame when the game is over.

Output:

The program will open a window displaying the Snake game. You can control the snake’s direction using the arrow keys and try to eat the food (white square) while avoiding collisions with the screen boundaries and the snake’s own body. The game will end when you hit a boundary or collide with yourself, and your score will be displayed in the terminal where you executed the program.

This program provides a basic example of game development in Python using the Pygame library.


31: Hangman Game

import random

# List of words for the game
word_list = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "kiwi", "lemon"]

# Choose a random word from the list
random_word = random.choice(word_list)

# Create a list to store guessed letters
guessed_letters = []

# Number of attempts allowed
max_attempts = 6
attempts = 0

# Create a list to store the progress of the word
progress = ["_"] * len(random_word)

while attempts < max_attempts and "_" in progress:
    # Display current progress
    print(" ".join(progress))

    # Get a letter guess from the player
    guess = input("Guess a letter: ").lower()

    if len(guess) == 1 and guess.isalpha():
        if guess in guessed_letters:
            print("You already guessed that letter.")
        elif guess in random_word:
            guessed_letters.append(guess)
            for i in range(len(random_word)):
                if random_word[i] == guess:
                    progress[i] = guess
        else:
            attempts += 1
            print(f"Wrong guess! {max_attempts - attempts} attempts left.")
    else:
        print("Invalid input. Please enter a single letter.")

if "_" not in progress:
    print(f"Congratulations! You guessed the word: {random_word}")
else:
    print(f"Sorry, you're out of attempts. The word was: {random_word}")

Explanation:

  • We start by defining a list of words for the Hangman game.
  • We choose a random word from the list using random.choice.
  • We create a list to store guessed letters and set the number of allowed attempts.
  • We initialize a progress list with underscores to represent the hidden word.
  • In a loop, we display the current progress and prompt the player to guess a letter.
  • We check if the guess is valid (a single letter) and whether it’s already guessed.
  • If the guess is correct, we update the progress list with the guessed letter.
  • If the guess is wrong, we decrement the remaining attempts and display a message.
  • The game continues until the player either guesses the word or runs out of attempts.
  • We display a win or lose message accordingly.

Output:

The program will run the Hangman game, allowing the player to guess letters for the hidden word. If the player correctly guesses all the letters within the maximum allowed attempts, they win and see a congratulatory message. If not, they see a message revealing the correct word.


32: Basic Image Processing (e.g., Grayscale)

from PIL import Image

# Open an image file
image = Image.open("sample.jpg")

# Convert the image to grayscale
grayscale_image = image.convert("L")

# Save the grayscale image
grayscale_image.save("grayscale_sample.jpg")

# Show the original and grayscale images
image.show()
grayscale_image.show()

Explanation:

  • We use the Python Imaging Library (PIL) to work with images.
  • We open an image file named “sample.jpg” using Image.open.
  • We convert the image to grayscale using the convert method with the mode “L,” which stands for grayscale.
  • We save the resulting grayscale image as “grayscale_sample.jpg.”
  • We display both the original and grayscale images using the show method.

Output:

The program will open and display two images: the original image and the grayscale version of the same image. The grayscale image will be saved as “grayscale_sample.jpg” in the same directory as the program.


33: Simple Chat Application (Client-Server)

Creating a basic chat application involving both a client and a server is a complex task that involves multiple Python scripts and modules. Here, I’ll provide an outline of how to create such an application and briefly explain its components:

Server Side (server.py):

import socket

# Create a socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a host and port
server_socket.bind(("127.0.0.1", 12345))

# Listen for incoming connections
server_socket.listen()

print("Server is listening...")

# Accept a connection from a client
client_socket, client_address = server_socket.accept()

# Receive and send messages
while True:
    data = client_socket.recv(1024).decode()
    print(f"Client: {data}")

    message = input("Server: ")
    client_socket.send(message.encode())

Client Side (client.py):

import socket

# Create a socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
client_socket.connect(("127.0.0.1", 12345))

# Receive and send messages
while True:
    data = client_socket.recv(1024).decode()
    print(f"Server: {data}")

    message = input("Client: ")
    client_socket.send(message.encode())

Explanation:

  • The server creates a socket, binds it to a host and port, and listens for incoming connections.
  • The client creates a socket and connects to the server.
  • Both the client and server continuously receive and send messages using recv and send methods.
  • The server listens on one port, and the client connects to that port.

Output:

When you run the server and client scripts, you’ll have a basic chat application where the server and client can send and receive messages to/from each other.


34: Basic Encryption and Decryption

from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Message to be encrypted
message = b"Hello, World!"

# Encrypt the message
encrypted_message = cipher_suite.encrypt(message)

# Decrypt the message
decrypted_message = cipher_suite.decrypt(encrypted_message)

print(f"Original Message: {message.decode()}")
print(f"Encrypted Message: {encrypted_message}")
print(f"Decrypted Message: {decrypted_message.decode()}")

Explanation:

  • We use the cryptography library to perform encryption and decryption.
  • We generate a key using Fernet.generate_key().
  • We create a cipher suite using the generated key.
  • We define a message to be encrypted as bytes.
  • We encrypt the message using the encrypt method of the cipher suite.
  • We decrypt the encrypted message using the decrypt method of the cipher suite.
  • We print the original message, encrypted message, and decrypted message.

Output:

The program will output the original message, the encrypted message (in bytes), and the decrypted message. The decrypted message should match the original message.


35: Basic Text-Based Adventure Game

Creating a text-based adventure game involves a significant amount of code and is best implemented as a standalone project. Here, I’ll provide a simplified outline of how you can structure such a game:

game.py:

class Player:
    def __init__(self):
        self.name

 = ""
        self.health = 100
        self.inventory = []

    def take_damage(self, damage):
        self.health -= damage

    def heal(self, amount):
        self.health += amount

    def add_to_inventory(self, item):
        self.inventory.append(item)

class Room:
    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.exits = {}
        self.items = []

    def add_exit(self, direction, room):
        self.exits[direction] = room

    def add_item(self, item):
        self.items.append(item)

class Item:
    def __init__(self, name, description):
        self.name = name
        self.description = description

def main():
    # Initialize game objects (rooms, items, etc.)
    # Implement game logic (moving between rooms, interacting with items, etc.)
    # Implement game loop

if __name__ == "__main__":
    main()

Explanation:

  • This code sets up the basic structure for a text-based adventure game, including classes for the player, rooms, and items.
  • The Player class defines attributes and methods for the player, such as health, inventory, and actions like taking damage and adding items to the inventory.
  • The Room class defines rooms in the game, including their exits and items.
  • The Item class represents items that can be found in rooms or added to the player’s inventory.
  • The main function serves as the entry point for the game and is where you would implement the game logic, such as defining rooms and interactions between the player and the game world.
  • The actual game content and logic would be implemented within the main function, including creating rooms, defining items, and handling player input.
  • The game loop, which continuously takes player input and updates the game state, would also be implemented within main.

Please note that creating a complete text-based adventure game is a substantial project and involves designing the game world, writing dialogues, and implementing various game mechanics.


36: Basic Text-to-Speech Converter

import pyttsx3

# Initialize the text-to-speech engine
engine = pyttsx3.init()

# Text to be converted to speech
text = "Hello, I am a text-to-speech converter."

# Convert and play the text as speech
engine.say(text)
engine.runAndWait()

Explanation:

  • We use the pyttsx3 library to perform text-to-speech conversion.
  • We initialize the text-to-speech engine using pyttsx3.init().
  • We define the text that we want to convert to speech in the text variable.
  • We use engine.say(text) to convert the text to speech.
  • Finally, we use engine.runAndWait() to play the converted speech.

Output:

When you run the program, you will hear the text “Hello, I am a text-to-speech converter.” spoken out loud by the computer.


37: Basic Speech Recognition

import speech_recognition as sr

# Initialize the recognizer
recognizer = sr.Recognizer()

# Capture audio from the microphone
with sr.Microphone() as source:
    print("Speak something:")
    audio = recognizer.listen(source)

try:
    # Recognize speech using Google Web Speech API
    text = recognizer.recognize_google(audio)
    print(f"You said: {text}")
except sr.UnknownValueError:
    print("Sorry, I couldn't understand your speech.")
except sr.RequestError:
    print("Sorry, there was an issue with the speech recognition service.")

Explanation:

  • We use the speech_recognition library to perform speech recognition.
  • We initialize the recognizer using sr.Recognizer().
  • We capture audio from the microphone using a context manager (with sr.Microphone() as source).
  • The user is prompted to speak something.
  • We use recognizer.listen(source) to capture the audio input.
  • We attempt to recognize the speech using Google’s Web Speech API (recognizer.recognize_google(audio)).
  • If speech is recognized, we print the recognized text. If not, we handle potential errors.

Output:

When you run the program, it will capture your spoken words and attempt to recognize them. If it successfully recognizes the speech, it will print the recognized text. Otherwise, it will print an error message.


38: Create a Quiz Game

Creating a quiz game is a more involved project that typically requires creating questions, answers, and implementing game logic. Here, I’ll provide a simplified outline of how to structure such a game:

quiz_game.py:

class Question:
    def __init__(self, text, choices, correct_choice):
        self.text = text
        self.choices = choices
        self.correct_choice = correct_choice

    def check_answer(self, answer):
        return answer == self.correct_choice

class Quiz:
    def __init__(self, questions):
        self.questions = questions
        self.score = 0

    def start_quiz(self):
        for i, question in enumerate(self.questions, start=1):
            print(f"Question {i}: {question.text}")
            for j, choice in enumerate(question.choices, start=1):
                print(f"{j}. {choice}")
            answer = input("Enter your choice (1-4): ")
            if question.check_answer(answer):
                print("Correct!\n")
                self.score += 1
            else:
                print("Incorrect.\n")
        print(f"Quiz completed! Your score: {self.score}/{len(self.questions)}")

def main():
    # Define quiz questions
    questions = [
        Question("What is 2 + 2?", ["1", "2", "3", "4"], "4"),
        Question("Which planet is known as the Red Planet?", ["Earth", "Mars", "Venus", "Jupiter"], "Mars"),
        # Add more questions here
    ]

    # Create a quiz and start it
    quiz = Quiz(questions)
    quiz.start_quiz()

if __name__ == "__main__":
    main()

Explanation:

  • This code sets up the basic structure for a text-based quiz game, including classes for questions and the quiz itself.
  • The Question class represents a single quiz question with text, multiple choices, and the correct choice.
  • The Quiz class manages a collection of questions and keeps track of the player’s score.
  • The start_quiz method of the Quiz class presents each question to the player, evaluates their answers, and calculates the final score.
  • The main function serves as the entry point for the game and is where you would define quiz questions, create the quiz, and start the game.
  • You can add more questions to the questions list to expand the quiz.

Please note that creating a complete quiz game involves designing questions, handling user input, and implementing various game mechanics.


39: Basic Email Sending Application

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Sender's email address and password (for Gmail)
sender_email = "youremail@gmail.com"
sender_password = "yourpassword"

# Recipient's email address
recipient_email = "recipient@example.com"

# Create a MIMEText object for the email content
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = "Sample Email Subject"
body = "This is a sample email body."
message.attach(MIMEText(body, 'plain'))

# Connect to the SMTP server (for Gmail)
try:
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
except Exception as e:
    print(f"Failed to connect to the SMTP server: {str(e)}")

# Send the email
try:
    server.sendmail(sender_email, recipient_email, message.as_string())
    print("Email sent successfully!")
except Exception as e:
    print(f"Failed to send the email: {str(e)}")

# Quit the server
server.quit()

Explanation:

  • This program demonstrates sending an email using the Simple Mail Transfer Protocol (SMTP) with the smtplib library.
  • Replace youremail@gmail.com and yourpassword with your actual email address and password for the sender’s Gmail account.
  • Specify the recipient’s email address in the recipient_email variable.
  • We create an email message using the MIMEMultipart class and set the sender, recipient, and subject.
  • The email body is created as plain text and attached to the message.
  • We connect to the Gmail SMTP server (you can replace this with the SMTP server of your email provider) and login using the sender’s email and password. Please note that using your actual email and password directly in code is not recommended for security reasons. In practice, you should use environment variables or a more secure method to store and retrieve credentials.
  • We send the email using server.sendmail and print a success message if the email is sent successfully.
  • Finally, we quit the SMTP server connection.

Output:

When you run the program and the email is sent successfully, you will see the message “Email sent successfully!” printed in the console.


40: Simple Alarm Clock

import time
import winsound

# Function to set the alarm
def set_alarm():
    try:
        # Input time for alarm in 24-hour format (e.g., "08:00" for 8:00 AM)
        alarm_time = input("Enter the time for the alarm (HH:MM): ")
        while True:
            current_time = time.strftime("%H:%M")
            if current_time == alarm_time:
                print("Time to wake up!")
                winsound.Beep(1000, 1000)  # Beep sound for 1 second
                break
            time.sleep(60)  # Check every minute
    except KeyboardInterrupt:
        print("\nAlarm clock stopped.")

# Main program
if __name__ == "__main__":
    set_alarm()

Explanation:

  • This program allows you to set a simple alarm clock by specifying the time you want to be alerted.
  • The set_alarm function takes the input time for the alarm in 24-hour format (e.g., “08:00” for 8:00 AM).
  • The program continuously checks the current time using time.strftime("%H:%M") and compares it to the specified alarm time.
  • If the current time matches the alarm time, it prints “Time to wake up!” and generates a beep sound using winsound.Beep(1000, 1000) (a 1-second beep sound). You can adjust the frequency (1000) and duration (1000) to customize the beep.
  • The program checks the time every minute using time.sleep(60).
  • The alarm clock can be stopped by pressing Ctrl+C (KeyboardInterrupt).

Output:

When you run the program, it will prompt you to enter the time for the alarm. Once the specified time is reached, it will display “Time to wake up!” and produce a beep sound. You can stop the alarm by pressing Ctrl+C.

Please note that this is a simple command-line alarm clock, and you can customize it further to meet your specific needs.


41: Basic Currency Converter

import requests

# Currency conversion function
def convert_currency(amount, from_currency, to_currency):
    # Define the API endpoint
    url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"

    try:
        # Send a GET request to the API
        response = requests.get(url)
        data = response.json()
        conversion_rate = data['rates'][to_currency]

        # Perform the conversion
        converted_amount = amount * conversion_rate

        return converted_amount
    except Exception as e:
        return f"Error: {str(e)}"

# Example usage
amount = 100  # Amount to convert
from_currency = "USD"  # Convert from US Dollars
to_currency = "EUR"  # Convert to Euros

result = convert_currency(amount, from_currency, to_currency)
print(f"{amount} {from_currency} is equal to {result} {to_currency}")

Explanation:

  • This program demonstrates a basic currency converter using exchange rate data from an external API.
  • We define a convert_currency function that takes the amount to convert, the source currency (from_currency), and the target currency (to_currency).
  • Inside the function, we construct the API endpoint for retrieving exchange rate data for the source currency.
  • We send a GET request to the API and parse the response as JSON.
  • We extract the conversion rate for the target currency from the API response and perform the currency conversion.
  • The converted amount is returned as the result.
  • In the example usage, we convert 100 US Dollars (USD) to Euros (EUR).
  • The result is printed as “100 USD is equal to X.XX EUR.”
  • Please note that this is a simplified example, and real-world currency converters may involve more complex logic and error handling.

Output:

The program will output the converted amount, such as “100 USD is equal to X.XX EUR.”


42: Basic HTML Parser

from html.parser import HTMLParser

# Create a custom HTML parser
class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print(f"Start tag: {tag}")

    def handle_endtag(self, tag):
        print(f"End tag: {tag}")

    def handle_data(self, data):
        print(f"Data: {data}")

# Example HTML content
html_content = "<html><head><title>Sample Page</title></head><body><h1>Welcome</h1><p>This is a sample page.</p></body></html>"

# Initialize the parser and parse the HTML
parser = MyHTMLParser()
parser.feed(html_content)

Explanation:

  • This program demonstrates a basic HTML parser using the HTMLParser class from the html.parser module.
  • We create a custom HTML parser class MyHTMLParser that inherits from HTMLParser and overrides methods like handle_starttag, handle_endtag, and handle_data to handle different parts of the HTML.
  • In the handle_starttag method, we print the start tag encountered.
  • In the handle_endtag method, we print the end tag encountered.
  • In the handle_data method, we print the data (text content) encountered.
  • We provide an example HTML content (html_content) that includes tags like <html>, <head>, <title>, <body>, <h1>, and <p>.
  • We initialize the custom parser and parse the HTML content using parser.feed(html_content).

Output:

The program will parse the example HTML content and print information about the start tags, end tags, and data encountered in the HTML.


43: Basic RSS Reader

import feedparser

# RSS feed URL
rss_url = "https://example.com/rss-feed.xml"

# Parse the RSS feed
feed = feedparser.parse(rss_url)

# Print the feed title and description
print("Feed Title:", feed.feed.title)
print("Feed Description:", feed.feed.description)

# Print the latest entries
print("\nLatest Entries:")
for entry in feed.entries:
    print(entry.title)
    print(entry.link)
    print(entry.published)
    print()

Explanation:

  • This program demonstrates a basic RSS reader using the feedparser library, which allows you to parse and extract information from RSS feeds.
  • We specify the URL of the RSS feed in the rss_url variable.
  • We use feedparser.parse(rss_url) to parse the RSS feed and store the parsed data in the feed object.
  • We print the feed’s title and description using feed.feed.title and feed.feed.description.
  • We loop through the latest entries in the RSS feed using feed.entries and print details like the entry title, link, and published date.
  • You can replace the rss_url variable with the URL of the RSS feed you want to read.

Output:

The program will retrieve and parse the RSS feed, then print the feed

‘s title, description, and the latest entries’ details, including titles, links, and publication dates.


44: Basic AI Chatbot

import random

# List of chatbot responses
responses = {
    "hello": "Hello! How can I assist you today?",
    "how are you": "I'm just a computer program, but thanks for asking!",
    "bye": "Goodbye! Have a great day!",
    "default": "I'm not sure how to respond to that."
}

# Function to get a response from the chatbot
def get_response(user_input):
    user_input = user_input.lower()
    return responses.get(user_input, responses["default"])

# Main chat loop
print("Chatbot: Hello! How can I assist you today?")
while True:
    user_input = input("You: ")
    if user_input.lower() == "bye":
        print("Chatbot: Goodbye! Have a great day!")
        break
    response = get_response(user_input)
    print("Chatbot:", response)

Explanation:

  • This program demonstrates a basic AI chatbot that responds to user input with predefined responses.
  • We define a dictionary called responses that maps user inputs (in lowercase) to chatbot responses. There’s also a default response for inputs that the chatbot doesn’t recognize.
  • The get_response function takes user input, converts it to lowercase, and retrieves the corresponding response from the responses dictionary.
  • The main chat loop repeatedly prompts the user for input and prints the chatbot’s response.
  • The chatbot responds to inputs such as “hello,” “how are you,” and “bye.”
  • The loop continues until the user inputs “bye.”

Output:

When you run the program, you can engage in a simple conversation with the chatbot. It will respond to your inputs with the predefined responses.


45: Basic Music Player

Creating a basic music player typically involves using external libraries or modules for audio playback. Below is an outline of how you can create a simple command-line music player using the pygame library. Please note that you will need to install pygame using pip install pygame if you haven’t already.

import pygame

# Initialize the Pygame mixer
pygame.mixer.init()

# Load a music file (replace 'music.mp3' with the path to your music file)
pygame.mixer.music.load('music.mp3')

# Play the music
pygame.mixer.music.play()

# Pause the music (uncomment the following line to pause)
# pygame.mixer.music.pause()

# Resume the music (uncomment the following line to resume)
# pygame.mixer.music.unpause()

# Stop the music (uncomment the following line to stop)
# pygame.mixer.music.stop()

# Wait for the music to finish
pygame.mixer.music.wait()

Explanation:

  • This program demonstrates a basic music player using the pygame library.
  • We initialize the Pygame mixer using pygame.mixer.init().
  • You should replace 'music.mp3' with the path to your music file.
  • We load the music file using pygame.mixer.music.load().
  • We play the music using pygame.mixer.music.play().
  • You can pause, resume, or stop the music by uncommenting the respective lines of code.
  • We use pygame.mixer.music.wait() to wait for the music to finish playing before the program exits.

Output:

When you run the program, it will play the specified music file using the pygame library. You can customize the program by adding more features like a playlist or user controls (play, pause, stop, skip tracks, etc.), depending on your requirements.

Please note that creating a full-featured music player with a graphical user interface (GUI) is a more complex project and typically involves additional libraries and modules for the GUI components.


Certainly, let’s continue with the explanations and simplified examples for programs 46 to 60:

46: Basic Video Player

Creating a basic video player typically involves using external libraries or modules for video playback. Below is an outline of how you can create a simple video player using the pygame library. Please note that you will need to install pygame using pip install pygame if you haven’t already.

import pygame

# Initialize Pygame
pygame.init()

# Create a Pygame display
screen = pygame.display.set_mode((640, 480))

# Load a video file (replace 'video.mp4' with the path to your video file)
video = pygame.movie.Movie('video.mp4')

# Play the video
video.play()

# Main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Update the display
    screen.blit(video.get_surface(), (0, 0))
    pygame.display.update()

# Quit Pygame
pygame.quit()

Explanation:

  • This program demonstrates a basic video player using the pygame library.
  • We initialize Pygame using pygame.init().
  • We create a Pygame display with a specified size.
  • You should replace 'video.mp4' with the path to your video file.
  • We load the video file using pygame.movie.Movie().
  • We play the video using video.play().
  • The main loop continuously updates the display to show the video frames.
  • The program exits when the user closes the window.

Output:

When you run the program, it will play the specified video file using the pygame library. You can customize the program further by adding features like video controls (play, pause, stop, seek), volume control, and user interface components, depending on your requirements.

Creating a full-featured video player with advanced features and a graphical user interface (GUI) would involve more complex code and likely additional libraries or modules.


47: Basic Web Browser

Creating a basic web browser is a complex task that typically involves using web browser engines like Chromium or embedding a browser component. Building a complete web browser from scratch is beyond the scope of a simple example. However, you can create a basic web browser interface using a library like Tkinter and display web content using a WebView component provided by a web framework like Qt or wxPython. Here’s a simplified example using Tkinter:

import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
import webbrowser

# Create the main application window
app = tk.Tk()
app.title("Basic Web Browser")

# Function to open a web page
def open_webpage():
    url = url_entry.get()
    try:
        webbrowser.open(url)
    except Exception as e:
        messagebox.showerror("Error", f"Failed to open URL: {str(e)}")

# Create and pack widgets
url_label = ttk.Label(app, text="Enter URL:")
url_label.pack(pady=10)
url_entry = ttk.Entry(app, width=40)
url_entry.pack()
go_button = ttk.Button(app, text="Go", command=open_webpage)
go_button.pack(pady=10)

# Run the application
app.mainloop()

Explanation:

  • This program demonstrates a basic web browser interface using Tkinter.
  • We create the main application window using tk.Tk().
  • The open_webpage function is called when the “Go” button is clicked. It opens the URL entered in the entry field using the webbrowser.open function.
  • Widgets like labels, entry fields, and buttons are created using tkinter and ttk (Themed Tkinter).
  • We pack the widgets to arrange them in the application window.
  • The application runs in a loop until the user closes the window.

Output:

When you run the program, it will display a basic web browser interface with an entry field where you can enter a URL and a “Go” button to open the web page in your default web browser. Please note that this is a very simplified example, and real web browsers are much more complex.


48: Basic 2D Graphics (Drawing Shapes)

import pygame

# Initialize Pygame
pygame.init()

# Create a Pygame display
screen = pygame.display.set_mode((640, 480))

# Set the background color
background_color = (255, 255, 255)

# Main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the background with the background color
    screen.fill(background_color)

    # Draw a red rectangle (x, y, width, height)
    pygame.draw.rect(screen, (255, 0, 0), (100, 100, 200, 150))

    # Draw a green circle (x, y, radius)
    pygame.draw.circle(screen, (0, 255, 0), (400, 300), 50)

    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()

Explanation:

  • This program demonstrates basic 2D graphics using the pygame library.
  • We initialize Pygame using pygame.init().
  • We create a Pygame display with a specified size.
  • We set the background color to white using background_color.
  • The main loop continuously updates the display, fills it with the background color, and draws shapes.
  • We use pygame.draw.rect to draw a red rectangle and pygame.draw.circle to draw a green circle.
  • The program exits when the user closes the window.

Output:

When you run the program, it will display a window with a white background and draw a red rectangle and a green circle on the screen.

You can customize the program by adding more shapes, colors, and interactivity.


49: Basic 2D Animation

import pygame

# Initialize Pygame
pygame.init()

# Create a Pygame display
screen = pygame.display.set_mode((640, 480))

# Set the background color
background_color = (255, 255, 255)

# Define a red rectangle (x, y, width, height)
rect_x = 100
rect_y = 100
rect_width = 200
rect_height = 150

# Define initial animation variables
dx = 5  # Horizontal movement speed
dy = 5  # Vertical movement speed

# Main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the background with the background color
    screen.fill(background_color)

    # Draw a red rectangle at the current position
    pygame.draw.rect(screen, (255, 0, 0), (rect_x, rect_y, rect_width, rect_height))

    # Update the rectangle's position
    rect_x += dx
    rect_y += dy

    # Check for collision with the screen edges
    if rect_x < 

0 or rect_x + rect_width > 640:
        dx = -dx
    if rect_y < 0 or rect_y + rect_height > 480:
        dy = -dy

    # Update the display
    pygame.display.update()

    # Add a small delay to control animation speed
    pygame.time.delay(20)

# Quit Pygame
pygame.quit()

Explanation:

  • This program demonstrates basic 2D animation using the pygame library.
  • We initialize Pygame using pygame.init().
  • We create a Pygame display with a specified size.
  • We set the background color to white using background_color.
  • We define a red rectangle’s position (rect_x and rect_y) and dimensions (rect_width and rect_height).
  • We define initial animation variables dx and dy to control the rectangle’s movement.
  • The main loop continuously updates the display, moves the rectangle, and checks for collisions with the screen edges.
  • We use pygame.draw.rect to draw the red rectangle.
  • The program exits when the user closes the window.
  • We add a small delay using pygame.time.delay(20) to control the animation speed.

Output:

When you run the program, it will display a window with a white background and animate a red rectangle moving within the window. The rectangle will bounce off the screen edges due to collision detection.

You can customize the program by changing the initial position, size, colors, and animation speed.


50: Basic 2D Physics Simulation

Creating a basic 2D physics simulation typically involves modeling physical properties and applying forces to objects. Below is a simplified example of a bouncing ball simulation using the pygame library:

import pygame

# Initialize Pygame
pygame.init()

# Create a Pygame display
screen = pygame.display.set_mode((640, 480))

# Set the background color
background_color = (255, 255, 255)

# Define the ball's properties
ball_radius = 20
ball_x = 320
ball_y = 240
ball_speed_x = 5
ball_speed_y = 5
gravity = 0.2

# Main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the background with the background color
    screen.fill(background_color)

    # Draw the ball
    pygame.draw.circle(screen, (255, 0, 0), (ball_x, ball_y), ball_radius)

    # Update the ball's position
    ball_x += ball_speed_x
    ball_y += ball_speed_y

    # Apply gravity
    ball_speed_y += gravity

    # Check for collisions with screen edges
    if ball_x - ball_radius < 0 or ball_x + ball_radius > 640:
        ball_speed_x = -ball_speed_x

    if ball_y - ball_radius < 0 or ball_y + ball_radius > 480:
        ball_speed_y = -ball_speed_y

    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()

Explanation:

  • This program demonstrates a basic 2D physics simulation of a bouncing ball using the pygame library.
  • We initialize Pygame using pygame.init().
  • We create a Pygame display with a specified size.
  • We set the background color to white using background_color.
  • We define the ball’s properties, including its position (ball_x and ball_y), radius (ball_radius), initial speeds (ball_speed_x and ball_speed_y), and gravity (gravity).
  • The main loop continuously updates the display, moves the ball, applies gravity, and checks for collisions with the screen edges.
  • We use pygame.draw.circle to draw the red ball.
  • The program exits when the user closes the window.

Output:

When you run the program, it will display a window with a white background and simulate a red ball bouncing within the window. The ball’s motion is affected by gravity, and it bounces off the screen edges.

You can customize the program by adjusting the ball’s properties and the behavior of the physics simulation.


51: Simple Digital Clock

import tkinter as tk
from time import strftime

# Create the main application window
app = tk.Tk()
app.title("Digital Clock")

# Function to update the time
def time():
    string = strftime('%H:%M:%S %p')
    label.config(text=string)
    label.after(1000, time)

# Create a label for the time display
label = tk.Label(app, font=('calibri', 40, 'bold'), background='black', foreground='white')
label.pack(anchor='center')

# Run the time update function
time()

# Run the application
app.mainloop()

Explanation:

  • This program demonstrates a simple digital clock using Tkinter.
  • We create the main application window using tk.Tk().
  • The time function is responsible for updating the time display. It retrieves the current time using strftime, updates the label’s text, and schedules itself to run again after 1 second (1000 milliseconds).
  • We create a label widget (label) to display the time. We configure the label’s font, background color, and foreground color.
  • The label’s text is initially set to the current time using time().
  • The application’s main loop continuously updates the time display and runs until the user closes the window.

Output:

When you run the program, it will display a simple digital clock that updates in real-time to show the current time.

You can customize the clock’s appearance and format by adjusting the label’s properties and the strftime format string.


52: Basic Regular Expression Matcher

import re

# Sample text
text = "The quick brown fox jumps over the lazy dog."

# Regular expression pattern to match words starting with 'q' or 'b'
pattern = r'\b[qb]\w+'

# Find all matches
matches = re.findall(pattern, text)

# Print the matches
print(matches)

Explanation:

  • This program demonstrates basic regular expression matching using the re module in Python.
  • We define a sample text in the text variable.
  • The regular expression pattern r'\b[qb]\w+' is used to match words that start with either ‘q’ or ‘b’. Let’s break down the pattern:
  • \b indicates a word boundary.
  • [qb] matches either ‘q’ or ‘b’.
  • \w+ matches one or more word characters (letters, digits, or underscores).
  • We use re.findall(pattern, text) to find all matches of the pattern in the text.
  • The program prints the matched words.

Output:

When you run the program, it will find and print all words in the sample text that start with ‘q’ or ‘b’.

You can customize the regular expression pattern to match different patterns within text data.


53: Basic Password Generator

import random
import string

# Function to generate a random password
def generate_password(length):
    characters = string.ascii

_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

# Generate a random password with a length of 12 characters
password = generate_password(12)

# Print the generated password
print("Generated Password:", password)

Explanation:

  • This program demonstrates a basic password generator that generates random passwords.
  • The generate_password function takes a length parameter, which specifies the length of the generated password.
  • The function creates a pool of characters to choose from, which includes letters (both uppercase and lowercase), digits, and punctuation symbols.
  • It uses random.choice to select characters randomly from the pool and concatenates them to form the password.
  • The generated password is printed to the console.

Output:

When you run the program, it will generate a random password with the specified length (in this case, 12 characters) and print the generated password.

You can customize the password length by changing the argument passed to generate_password.


54: Basic URL Shortener

URL shortening typically involves interacting with a URL shortening service’s API. Here’s a simplified example using the pyshorteners library to shorten a URL:

First, you’ll need to install the pyshorteners library using pip install pyshorteners.

import pyshorteners

# Create a URL shortener object
s = pyshorteners.Shortener()

# URL to be shortened
url = "https://www.example.com/very/long/url/to/be/shortened"

# Shorten the URL
short_url = s.tinyurl.short(url)

# Print the shortened URL
print("Shortened URL:", short_url)

Explanation:

  • This program demonstrates a basic URL shortener using the pyshorteners library.
  • We create a URL shortener object using pyshorteners.Shortener().
  • The URL to be shortened is specified in the url variable.
  • We use the s.tinyurl.short(url) method to shorten the URL using the TinyURL shortening service (you can choose from various supported services).
  • The shortened URL is printed to the console.

Output:

When you run the program, it will shorten the specified URL using the chosen URL shortening service (in this case, TinyURL) and print the shortened URL.

You can customize the program by choosing a different URL shortening service or by integrating with a URL shortening API for more advanced features.


55: Simple Unit Converter

# Function to convert length from meters to feet
def meters_to_feet(meters):
    feet = meters * 3.28084
    return feet

# Function to convert temperature from Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

# Function to convert weight from kilograms to pounds
def kilograms_to_pounds(kilograms):
    pounds = kilograms * 2.20462
    return pounds

# Example conversions
length_meters = 5
temperature_celsius = 25
weight_kilograms = 10

length_feet = meters_to_feet(length_meters)
temperature_fahrenheit = celsius_to_fahrenheit(temperature_celsius)
weight_pounds = kilograms_to_pounds(weight_kilograms)

# Print the converted values
print(f"{length_meters} meters is equal to {length_feet:.2f} feet.")
print(f"{temperature_celsius} degrees Celsius is equal to {temperature_fahrenheit:.2f} degrees Fahrenheit.")
print(f"{weight_kilograms} kilograms is equal to {weight_pounds:.2f} pounds.")

Explanation:

  • This program demonstrates a simple unit converter that converts lengths from meters to feet, temperatures from Celsius to Fahrenheit, and weights from kilograms to pounds.
  • We define three conversion functions (meters_to_feet, celsius_to_fahrenheit, and kilograms_to_pounds) for each unit conversion.
  • Example values are provided for length (5 meters), temperature (25 degrees Celsius), and weight (10 kilograms) that we want to convert.
  • The functions are called with these values to perform the conversions.
  • The converted values are printed to the console with appropriate units and formatting.

Output:

When you run the program, it will calculate and print the converted values for length, temperature, and weight based on the provided examples.

You can customize the program by adding more conversion functions or handling different types of units.


56: Basic URL Validator

import re

# Function to validate a URL
def is_valid_url(url):
    # Regular expression pattern for URL validation
    pattern = re.compile(r'https?://(www\.)?[\w\.-]+\.\w+(/\S*)?')

    # Check if the URL matches the pattern
    if re.match(pattern, url):
        return True
    else:
        return False

# Example URLs to validate
urls = ["https://www.example.com", "ftp://invalid-url.com", "https://sub.domain.net/path"]

# Validate each URL and print the result
for url in urls:
    if is_valid_url(url):
        print(f"{url} is a valid URL.")
    else:
        print(f"{url} is not a valid URL.")

Explanation:

  • This program demonstrates a basic URL validator using regular expressions.
  • The is_valid_url function takes a URL as input and validates it using a regular expression pattern.
  • The regular expression pattern r'https?://(www\.)?[\w\.-]+\.\w+(/\S*)?' is used to match URLs with the following characteristics:
  • Starts with “http://” or “https://”
  • Optionally starts with “www.”
  • Contains one or more word characters, dots, or hyphens in the domain name.
  • May include a path segment after the domain.
  • The program provides a list of example URLs to validate.
  • For each URL, the is_valid_url function is called, and the result is printed to the console.

Output:

When you run the program, it will validate each example URL and print whether it is a valid URL or not based on the regular expression pattern.

You can customize the program by adding more URLs to validate or by modifying the regular expression pattern to match specific URL formats.


57: Basic QR Code Generator

To generate QR codes, you can use external libraries like qrcode. First, you’ll need to install the qrcode library using pip install qrcode.

import qrcode

# Data to encode in the QR code
data = "https://www.example.com"

# Generate a QR code
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data(data)
qr.make(fit=True)

# Create an image from the QR code
qr_img = qr.make_image(fill_color="black", back_color="white")

# Save the QR code image
qr_img.save("qrcode_example.png")

# Print a message
print("QR code generated and saved as 'qrcode_example.png'.")

Explanation:

  • This program demonstrates a basic QR code generator using the qrcode library.
  • We specify the data to be encoded in the QR code in the data variable (in this case, a URL).
  • We create a QR code object using qrcode.QRCode and configure its properties, including version, error correction level, box size, and border.
  • The data is added to the QR code using qr.add_data(data).
  • We use qr.make_image to generate an image from the QR code, specifying fill and background colors.
  • The generated QR code image is saved as “qrcode_example.png.”
  • A message is printed to indicate that the QR code has been generated and saved.

Output:

When you run the program, it will generate a QR code based on the provided data (a URL in this case) and save it as “qrcode_example.png.” You can then use this image to share the QR code.

You can customize the program by changing the data to encode or adjusting the QR code properties.


58: Basic CAPTCHA Generator

Creating a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) involves generating a random image with distorted text that users must decipher. Here’s a simplified example using the captcha library. First, you’ll need to install the captcha library using pip install captcha.

from captcha.image import ImageCaptcha

# Create a CAPTCHA image generator
captcha = ImageCaptcha(width=200, height=100)

# Generate a random CAPTCHA text
captcha_text = "AB12CD"

# Generate a CAPTCHA image
captcha_image = captcha.generate(captcha_text)

# Save the CAPTCHA image
captcha_image.save("captcha_example.png")

# Print a message
print("CAPTCHA generated and saved as 'captcha_example.png'.")

Explanation:

  • This program demonstrates a basic CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) image generator using the captcha library.
  • We create a CAPTCHA image generator using captcha.ImageCaptcha and specify the image dimensions (width and height).
  • A random CAPTCHA text is generated and stored in the captcha_text variable (you can customize this text).
  • We generate a CAPTCHA image by calling captcha.generate(captcha_text).
  • The generated CAPTCHA image is saved as “captcha_example.png.”
  • A message is printed to indicate that the CAPTCHA has been generated and saved.

Output:

When you run the program, it will generate a CAPTCHA image with the specified text (in this case, “AB12CD”) and save it as “captcha_example.png.” CAPTCHAs are often used to prevent automated bots from accessing certain web services.

You can customize the program by changing the CAPTCHA text or adjusting the image dimensions.


59: Basic Image Resizer

To resize images in Python, you can use external libraries like Pillow. First, you’ll need to install the Pillow library using pip install Pillow.

from PIL import Image

# Open an image file
input_image = Image.open("input_image.jpg")

# Define the new size (width, height)
new_size = (400, 300)

# Resize the image
resized_image = input_image.resize(new_size)

# Save the resized image
resized_image.save("output_image.jpg")

# Print a message
print("Image resized and saved as 'output_image.jpg'.")

Explanation:

  • This program demonstrates a basic image resizer using the Pillow library (PIL, Python Imaging Library).
  • We open an existing image file using Image.open("input_image.jpg"). Replace “input_image.jpg” with the path to your image file.
  • We define the new size for the image as a tuple (width, height) in the new_size variable.
  • The resize method is used to resize the image to the specified dimensions.
  • The resized image is saved as “output_image.jpg” using resized_image.save("output_image.jpg").
  • A message is printed to indicate that the image has been resized and saved.

Output:

When you run the program, it will open an input image, resize it to the specified dimensions, and save the resized image as “output_image.jpg.” You can adjust the new_size variable to specify the desired width and height for the resized image.


60: Basic Image Cropper

To crop images in Python, you can use the Pillow library. First, you’ll need to install the Pillow library using pip install Pillow.

from PIL import Image

# Open an image file
input_image = Image.open("input_image.jpg")

# Define the cropping coordinates (left, upper, right, lower)
crop_box = (100, 100, 400, 300)

# Crop the image
cropped_image = input_image.crop(crop_box)

# Save the cropped image
cropped_image.save("cropped_image.jpg")

# Print a message
print("Image cropped and saved as 'cropped_image.jpg'.")

Explanation:

  • This program demonstrates a basic image cropper using the Pillow library (PIL, Python Imaging Library).
  • We open an existing image file using Image.open("input_image.jpg"). Replace “input_image.jpg” with the path to your image file.
  • We define the cropping coordinates as a tuple (left, upper, right, lower) in the crop_box variable. These coordinates specify the region of the image to be cropped.
  • The crop method is used to crop the image based on the specified coordinates.
  • The cropped image is saved as “cropped_image.jpg” using cropped_image.save("cropped_image.jpg").
  • A message is printed to indicate that the image has been cropped and saved.

Output:

When you run the program, it will open an input image, crop it based on the specified coordinates, and save the cropped image as “cropped_image.jpg.” You can adjust the crop_box variable to specify the desired cropping region.


Leave a Reply

Your email address will not be published. Required fields are marked *