Embarking on Python projects is an essential step in turning theoretical knowledge into practical skills. Python’s simplicity and versatility make it an ideal language for beginners to explore coding through hands-on projects. Starting with simple yet engaging tasks like calculators, games, and data processing tools helps reinforce programming concepts such as loops, conditionals, and functions. These projects not only help you learn the syntax but also teach you how to approach and solve real-world problems in a structured manner.

Beginner projects provide a platform to experiment with Python libraries, enhance problem-solving skills, and gain confidence in your abilities. For instance, you could create a Rock-Paper-Scissors game to understand decision-making or a Weather App to learn API integration. Each project is a stepping stone toward mastering programming, offering opportunities to explore and build upon your knowledge. Whether you’re automating small tasks or creating interactive games, these projects set the foundation for a strong coding journey.

1. Building a Rock, Paper, Scissors Game in Python

Essential Tools and Setup

To build this game, you’ll need the following:

  1. Text Editor or IDE: Any editor like Visual Studio Code, PyCharm, or even IDLE will work.
  2. Python Installation: Ensure Python is installed on your computer.
  3. Basic Python Knowledge: Familiarity with concepts like variables, loops, conditional statements, and functions.

Step-by-Step Guide

Step 1: Set Up Your Project

  • Create a new Python file named rock_paper_scissors.py.
  • This file will contain all the code for your game.

Step 2: Define the Game Rules

  • Define the rules for Rock, Paper, Scissors:
    • Rock beats Scissors.
    • Scissors beats Paper.
    • Paper beats Rock.

Step 3: Import Required Modules

  • Use Python’s random module to let the computer make its choice.
python
import random

Step 4: Gather User Input

  • Ask the user to choose between Rock, Paper, or Scissors.
  • Convert their input to a standardized format (e.g., lowercase).
python
user_choice = input("Enter your choice (rock, paper, scissors): ").lower()

Step 5: Generate the Computer’s Choice

  • Use random.choice() to randomly select between Rock, Paper, and Scissors.
python
options = ["rock", "paper", "scissors"] computer_choice = random.choice(options)

Step 6: Compare Choices and Determine the Winner

  • Use conditional statements to decide the winner based on the rules.
python
if user_choice == computer_choice:
result = "It's a tie!"
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "scissors" and computer_choice == "paper") or \
(user_choice == "paper" and computer_choice == "rock"):
result = "You win!"
else:
result = "Computer wins!"

Step 7: Display the Results

  • Print the user’s choice, computer’s choice, and the result.
python
print(f"You chose: {user_choice}")

print(f"Computer chose: {computer_choice}")
print(result)

Step 8: Allow Repeated Play

  • Wrap the game logic in a loop so the user can play multiple rounds.
python
while True:
user_choice = input("Enter your choice (rock, paper, scissors): ").lower()
if user_choice not in options:
print("Invalid choice. Please try again.")
continue
computer_choice = random.choice(options)
print(f”You chose: {user_choice})
print(f”Computer chose: {computer_choice})if user_choice == computer_choice:
result = “It’s a tie!”
elif (user_choice == “rock” and computer_choice == “scissors”) or \
(user_choice == “scissors” and computer_choice == “paper”) or \
(user_choice == “paper” and computer_choice == “rock”):
result = “You win!”
else:
result = “Computer wins!”print(result)play_again = input(“Do you want to play again? (yes/no): “).lower()
if play_again != “yes”:
print(“Thanks for playing!”)
break

Advanced Features and Enhancements

  1. Error Handling:
    • Handle invalid inputs gracefully by prompting the user again.
  2. Scoreboard:
    • Track and display the score after each round (e.g., User: 2, Computer: 1).
  3. Custom Messages:
    • Add fun messages based on the outcomes.
  4. Graphical Interface:
    • Use the tkinter library to build a GUI for the game.

This will output something like:

plaintext
Enter your choice (rock, paper, scissors): rock
You chose: rock
Computer chose: scissors
You win!
Do you want to play again? (yes/no): yes
Enter your choice (rock, paper, scissors): paper
You chose: paper
Computer chose: rock
You win!
Do you want to play again? (yes/no): no
Thanks for playing!

2.Building a Calculator in Python

A calculator is a fundamental project to get hands-on experience with Python basics, including conditional statements, loops, and functions. This project supports various operations like addition, subtraction, multiplication, division, and more.

A Python calculator allows users to perform simple or advanced mathematical operations. It can be built using just basic syntax or extended to include error handling and advanced features like exponents or trigonometric calculations.

Step-by-Step Guide

Step 1: Define the Operations

Create basic operations like addition, subtraction, multiplication, and division.

python
def add(a, b):
return a + b
def subtract(a, b):
return a – bdef multiply(a, b):
return a * b

def divide(a, b):
if b == 0:
return “Error! Division by zero.”
return a / b

Step 2: Display Menu to the User

Provide a menu of operations to let the user choose.

python
def display_menu():
print("\nChoose an operation:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Exit")

Step 3: Get User Input

Prompt the user to enter two numbers and their desired operation.

python
def get_user_input():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
return num1, num2
except ValueError:
print("Invalid input! Please enter numbers only.")
return None, None

Step 4: Main Logic for the Calculator

Use a loop to keep the calculator running until the user chooses to exit.

python
def calculator():
while True:
display_menu()
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == ‘5’:
print(“Exiting the calculator. Goodbye!”)
breakif choice in [‘1’, ‘2’, ‘3’, ‘4’]:
num1, num2 = get_user_input()
if num1 is None or num2 is None:
continue

if choice == ‘1’:
print(f”The result is: {add(num1, num2)})
elif choice == ‘2’:
print(f”The result is: {subtract(num1, num2)})
elif choice == ‘3’:
print(f”The result is: {multiply(num1, num2)})
elif choice == ‘4’:
print(f”The result is: {divide(num1, num2)})
else:
print(“Invalid choice! Please select a valid option.”)

Complete Code

python
def add(a, b):
return a + b
def subtract(a, b):
return a – bdef multiply(a, b):
return a * b

def divide(a, b):
if b == 0:
return “Error! Division by zero.”
return a / b

def display_menu():
print(“\nChoose an operation:”)
print(“1. Addition (+)”)
print(“2. Subtraction (-)”)
print(“3. Multiplication (*)”)
print(“4. Division (/)”)
print(“5. Exit”)

def get_user_input():
try:
num1 = float(input(“Enter the first number: “))
num2 = float(input(“Enter the second number: “))
return num1, num2
except ValueError:
print(“Invalid input! Please enter numbers only.”)
return None, None

def calculator():
while True:
display_menu()
choice = input(“Enter your choice (1/2/3/4/5): “)

if choice == ‘5’:
print(“Exiting the calculator. Goodbye!”)
break

if choice in [‘1’, ‘2’, ‘3’, ‘4’]:
num1, num2 = get_user_input()
if num1 is None or num2 is None:
continue

if choice == ‘1’:
print(f”The result is: {add(num1, num2)})
elif choice == ‘2’:
print(f”The result is: {subtract(num1, num2)})
elif choice == ‘3’:
print(f”The result is: {multiply(num1, num2)})
elif choice == ‘4’:
print(f”The result is: {divide(num1, num2)})
else:
print(“Invalid choice! Please select a valid option.”)

if __name__ == “__main__”:
calculator()

Features to Enhance the Calculator

  1. Advanced Operations: Add features like exponents, square roots, or logarithms.
  2. Error Handling: Gracefully handle invalid inputs and unexpected errors.
  3. GUI Version: Use libraries like tkinter or PyQt for a graphical interface.
  4. History: Save the results of all calculations in a session.
  5. Custom Functions: Allow users to define and save their custom functions.

 


3. Building a Basic Alarm Clock in Python

Creating a Basic Alarm Clock in Python is an excellent beginner project that combines Python’s time module and simple logic. This project helps you understand how to manage time-based tasks and interact with the system.

An alarm clock is a program that triggers a specific action (like a message or sound) at a set time. With Python, you can build a simple text-based alarm clock that checks the current time and notifies the user when it matches the alarm time.

Key Concepts Covered:

  • Working with the time module.
  • Taking and validating user input.
  • Implementing loops for time checks.

Step-by-Step Guide

Step 1: Import Required Modules

  • The time module allows you to work with the system clock.
python
import time

Step 2: Gather Alarm Details

  • Ask the user to input the time for the alarm in the HH:MM format.
python
alarm_time = input("Enter the alarm time (HH:MM): ")

Step 3: Validate and Parse Input

  • Ensure the input is in the correct format and convert it to hours and minutes.
python
try:
alarm_hour, alarm_minute = map(int, alarm_time.split(":"))
if 0 <= alarm_hour < 24 and 0 <= alarm_minute < 60:
print(f"Alarm set for {alarm_hour:02}:{alarm_minute:02}")
else:
print("Invalid time format. Please enter a valid time.")
exit()
except ValueError:
print("Invalid input. Please use the HH:MM format.")
exit()

Step 4: Implement the Alarm Logic

  • Continuously check the current time against the alarm time using a loop.
python
while True:
current_time = time.localtime() # Get the current time
current_hour = current_time.tm_hour
current_minute = current_time.tm_min
if current_hour == alarm_hour and current_minute == alarm_minute:
print(“Wake up! It’s time!”)
breaktime.sleep(30) # Check every 30 seconds to save resources

Step 5: Play an Alarm Sound (Optional)

  • Use the playsound library to play a sound when the alarm rings.
  • Install the library with pip install playsound.
python

from playsound import playsound

if current_hour == alarm_hour and current_minute == alarm_minute:
print(“Wake up! It’s time!”)
playsound(“alarm.mp3”) # Replace with the path to your audio file
break

Complete Code

Here’s the full code for a basic alarm clock:

python
import time
from playsound import playsound # Optional for sound notification
# Get alarm time from the user
alarm_time = input(“Enter the alarm time (HH:MM): “)# Validate and parse the input
try:
alarm_hour, alarm_minute = map(int, alarm_time.split(“:”))
if 0 <= alarm_hour < 24 and 0 <= alarm_minute < 60:
print(f”Alarm set for {alarm_hour:02}:{alarm_minute:02})
else:
print(“Invalid time format. Please enter a valid time.”)
exit()
except ValueError:
print(“Invalid input. Please use the HH:MM format.”)
exit()

# Alarm clock logic
while True:
current_time = time.localtime() # Get current time
current_hour = current_time.tm_hour
current_minute = current_time.tm_min

if current_hour == alarm_hour and current_minute == alarm_minute:
print(“Wake up! It’s time!”)
# Play a sound (optional)
# playsound(“alarm.mp3”)
break

time.sleep(30) # Check every 30 seconds

Enhancements and Features

  1. Custom Alarm Sound: Allow users to set their preferred sound.
  2. Snooze Feature: Add functionality to delay the alarm by a few minutes.
  3. Graphical Interface: Build a GUI for the alarm clock using tkinter.
  4. Recurring Alarms: Enable daily or weekly recurring alarms.

Sample Output

plaintext
Enter the alarm time (HH:MM): 07:30
Alarm set for 07:30
Wake up! It's time!
—————————————————————————————————————————

4. Building a BMI Calculator in Python

A Body Mass Index (BMI) Calculator is a simple Python project that calculates a user’s BMI based on their height and weight and categorizes the result according to standard BMI ranges.

BMI is a measure used to assess a person’s body weight relative to their height. The formula to calculate BMI is:
BMI=Weight (kg)Height (m)2\text{BMI} = \frac{\text{Weight (kg)}}{\text{Height (m)}^2}

The categories are generally defined as:

  • Underweight: BMI < 18.5
  • Normal weight: BMI 18.5–24.9
  • Overweight: BMI 25.0–29.9
  • Obesity: BMI ≥ 30.0

This project helps you practice user input, mathematical operations, and conditional statements in Python.

Step-by-Step Guide

Step 1: Gather User Input

Prompt the user to input their weight and height.

python
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))

Step 2: Calculate BMI

Use the BMI formula to calculate the value.

python
bmi = weight / (height ** 2)

Step 3: Categorize the Result

Use conditional statements to determine the BMI category.

python
if bmi < 18.5:
category = "Underweight"
elif 18.5 <= bmi < 25:
category = "Normal weight"
elif 25 <= bmi < 30:
category = "Overweight"
else:
category = "Obesity"

Step 4: Display the Result

Print the BMI and the corresponding category.

python
print(f"Your BMI is: {bmi:.2f}")
print(f"This is considered: {category}")

Complete Code

python

# BMI Calculator

# Get user input for weight and height
weight = float(input(“Enter your weight in kilograms: “))
height = float(input(“Enter your height in meters: “))

# Calculate BMI
bmi = weight / (height ** 2)

# Determine the BMI category
if bmi < 18.5:
category = “Underweight”
elif 18.5 <= bmi < 25:
category = “Normal weight”
elif 25 <= bmi < 30:
category = “Overweight”
else:
category = “Obesity”

# Display the results
print(f”\nYour BMI is: {bmi:.2f})
print(f”This is considered: {category})

Enhancements and Features

  1. Input Validation:
    • Ensure the user enters positive numbers for weight and height.
  2. Imperial Units Support:
    • Allow users to input weight in pounds and height in inches, then convert to metric:
      Weight (kg)=Weight (lbs)×0.453592\text{Weight (kg)} = \text{Weight (lbs)} \times 0.453592
      Height (m)=Height (in)×0.0254\text{Height (m)} = \text{Height (in)} \times 0.0254
  3. Personalized Feedback:
    • Provide tips based on the user’s BMI category.
  4. GUI Version:
    • Use the tkinter library to build a graphical user interface.
  5. Multiple Users:
    • Allow calculations for multiple users by looping or storing results in a list.

Sample Output

plaintext
Enter your weight in kilograms: 70
Enter your height in meters: 1.75
Your BMI is: 22.86
This is considered: Normal weight

5. Building a Weather App (CLI) in Python

A Weather App is a command-line interface (CLI) project that fetches and displays real-time weather information for a specified location. Using an API, you can retrieve data like temperature, humidity, and weather conditions.

This project combines API interaction, JSON data parsing, and Python’s ability to process and display information. You’ll use a weather API, such as OpenWeatherMap, to access current weather data.

Key Concepts Covered:

  • Using Python libraries for API requests (requests).
  • Parsing and handling JSON data.
  • Taking user input and displaying dynamic output.

Step-by-Step Guide

Step 1: Set Up the API

  1. Sign up for a free API key from OpenWeatherMap.
  2. Note the API endpoint for current weather data:
    bash
    http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_key}&units=metric

Step 2: Install Required Libraries

You’ll need the requests library to make API calls. Install it using:

bash
pip install requests

Step 3: Fetch Weather Data

Use the API to fetch weather data for a user-specified location.

python

import requests

API_KEY = “your_api_key” # Replace with your OpenWeatherMap API key
BASE_URL = “http://api.openweathermap.org/data/2.5/weather”

# Get city name from user
city_name = input(“Enter the city name: “)

# Construct the API request URL
url = f”{BASE_URL}?q={city_name}&appid={API_KEY}&units=metric”

# Make the API request
response = requests.get(url)

Step 4: Parse the JSON Response

Extract useful information like temperature, humidity, and weather conditions from the JSON data.

python
if response.status_code == 200:
data = response.json()
city = data["name"] temperature = data["main"]["temp"] humidity = data["main"]["humidity"] weather_description = data["weather"][0]["description"]
# Display the results
print(f”\nWeather in {city}:”)
print(f”Temperature: {temperature}°C”)
print(f”Humidity: {humidity}%”)
print(f”Condition: {weather_description.capitalize()})
else:
print(“City not found or an error occurred. Please try again.”)

Step 5: Handle Errors Gracefully

Add error handling for invalid inputs or API issues.

python
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
exit()

Complete Code

python

import requests

# Constants
API_KEY = “your_api_key” # Replace with your OpenWeatherMap API key
BASE_URL = “http://api.openweathermap.org/data/2.5/weather”

# Get city name from user
city_name = input(“Enter the city name: “)

# Construct the API request URL
url = f”{BASE_URL}?q={city_name}&appid={API_KEY}&units=metric”

try:
# Make the API request
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses

# Parse the JSON response
data = response.json()
city = data[“name”] temperature = data[“main”][“temp”] humidity = data[“main”][“humidity”] weather_description = data[“weather”][0][“description”]

# Display the weather information
print(f”\nWeather in {city}:”)
print(f”Temperature: {temperature}°C”)
print(f”Humidity: {humidity}%”)
print(f”Condition: {weather_description.capitalize()})
except requests.exceptions.RequestException as e:
print(f”An error occurred: {e})

Enhancements and Features

  1. Unit Options: Allow the user to choose between Celsius, Fahrenheit, or Kelvin.
  2. Forecast: Extend the app to display a 5-day forecast using the OpenWeatherMap API.
  3. Geolocation: Fetch weather for the user’s current location using IP-based geolocation APIs.
  4. GUI Version: Create a graphical weather app using tkinter or PyQt.
  5. Save History: Log previous searches and results to a file.

Sample Output

plaintext

Enter the city name: London

Weather in London:
Temperature: 12.34°C
Humidity: 81%
Condition: Clear sky

—————————————————————————————————————————

6. Building a Stock Price Tracker in Python

A Stock Price Tracker fetches real-time stock data and displays essential details such as the current price, daily high and low, and market trends. This project demonstrates how to interact with APIs, handle JSON data, and present dynamic updates in the terminal.

Stock tracking applications are widely used by traders and investors to monitor market trends. This project uses APIs like Yahoo Finance or Alpha Vantage to retrieve stock market data.

Step-by-Step Guide

Step 1: Set Up the Environment

  1. Install the required libraries:
bash
pip install requests yfinance
  1. Sign up for an API key if using a service like Alpha Vantage.

Step 2: Fetch Stock Data

Use a library like yfinance (Yahoo Finance) or requests for Alpha Vantage. Here’s an example using yfinance.

python

import yfinance as yf

# Get stock ticker from the user
stock_symbol = input(“Enter the stock symbol (e.g., AAPL, TSLA): “).upper()

# Fetch stock data
stock = yf.Ticker(stock_symbol)

# Get real-time data
stock_info = stock.info

Step 3: Display Stock Details

Extract and display useful details like the current price, daily high/low, and market cap.

python
try:
print(f"\nStock: {stock_info['shortName']} ({stock_symbol})")
print(f"Current Price: ${stock_info['currentPrice']}")
print(f"Daily High: ${stock_info['dayHigh']}")
print(f"Daily Low: ${stock_info['dayLow']}")
print(f"Market Cap: ${stock_info['marketCap']:,}")
print(f"52-Week High: ${stock_info['fiftyTwoWeekHigh']}")
print(f"52-Week Low: ${stock_info['fiftyTwoWeekLow']}")
except KeyError:
print("Invalid stock symbol or data not available.")

Step 4: Add Error Handling

Handle errors for invalid stock symbols or network issues.

python

import requests

try:
stock = yf.Ticker(stock_symbol)
stock_info = stock.info

if ‘currentPrice’ not in stock_info:
raise ValueError(“Invalid stock symbol or data not available.”)
except requests.exceptions.RequestException as e:
print(f”Network error: {e})
except ValueError as e:
print(e)

Step 5: Enhance with Live Updates

To track stock prices in real-time, implement a refresh loop.

python

import time

while True:
stock_info = stock.info
current_price = stock_info.get(‘currentPrice’, ‘N/A’)
print(f”Current Price of {stock_symbol}: ${current_price})
time.sleep(30) # Refresh every 30 seconds

Complete Code

Here’s the full implementation:

python
import yfinance as yf
import time
def get_stock_data(stock_symbol):
stock = yf.Ticker(stock_symbol)
stock_info = stock.info
return stock_infodef display_stock_data(stock_symbol):
try:
stock_info = get_stock_data(stock_symbol)
print(f”\nStock: {stock_info[‘shortName’]} ({stock_symbol})”)
print(f”Current Price: ${stock_info[‘currentPrice’]})
print(f”Daily High: ${stock_info[‘dayHigh’]})
print(f”Daily Low: ${stock_info[‘dayLow’]})
print(f”Market Cap: ${stock_info[‘marketCap’]:,})
print(f”52-Week High: ${stock_info[‘fiftyTwoWeekHigh’]})
print(f”52-Week Low: ${stock_info[‘fiftyTwoWeekLow’]})
except KeyError:
print(“Invalid stock symbol or data not available.”)
except Exception as e:
print(f”An error occurred: {e})

# Main Program
if __name__ == “__main__”:
stock_symbol = input(“Enter the stock symbol (e.g., AAPL, TSLA): “).upper()
while True:
display_stock_data(stock_symbol)
time.sleep(30) # Refresh every 30 seconds

Enhancements and Features

  1. Portfolio Tracker:
    • Track multiple stocks and display a summary.
  2. Historical Data Analysis:
    • Use the history() method in yfinance to fetch historical stock prices and plot graphs.
  3. Alert System:
    • Set alerts for price thresholds and notify the user.
  4. Integration with Alpha Vantage:
    • Use Alpha Vantage for more detailed stock and technical analysis data.
  5. GUI Version:
    • Build a graphical interface using tkinter or PyQt.

Sample Output

plaintext

Enter the stock symbol (e.g., AAPL, TSLA): AAPL

Stock: Apple Inc. (AAPL)
Current Price: $175.42
Daily High: $176.80
Daily Low: $173.50
Market Cap: $2,789,430,000,000
52-Week High: $198.23
52-Week Low: $124.45


7. Building a YouTube Video Downloader in Python

A YouTube Video Downloader allows you to fetch and download videos directly to your local system using Python. This project uses the pytube library, a powerful and beginner-friendly tool for interacting with YouTube videos.

YouTube Video Downloaders are great for saving videos for offline use. With this project, you can:

  1. Download videos in different resolutions.
  2. Download only the audio of a video (useful for music).
  3. Handle errors like invalid URLs gracefully.

Step-by-Step Guide

Step 1: Install the Required Library

The pytube library is essential for this project. Install it using pip:

bash
pip install pytube

Step 2: Fetch Video Information

Use pytube to get details about the video, such as title and available streams.

python

from pytube import YouTube

# Get YouTube video URL from the user
video_url = input(“Enter the YouTube video URL: “)

# Fetch video details
try:
yt = YouTube(video_url)
print(f”Title: {yt.title})
print(f”Views: {yt.views})
print(“Available Streams:”)
for stream in yt.streams.filter(progressive=True):
print(f”Resolution: {stream.resolution}, File Type: {stream.mime_type})
except Exception as e:
print(f”Error: {e})

Step 3: Allow the User to Choose a Resolution

Enable users to select the resolution they want to download.

python
# Display available resolutions
streams = yt.streams.filter(progressive=True)
for i, stream in enumerate(streams):
print(f"{i + 1}. Resolution: {stream.resolution}, File Type: {stream.mime_type}")
# Let the user choose a resolution
choice = int(input(“Enter the number of your choice: “)) – 1
selected_stream = streams[choice]

Step 4: Download the Video

Use the download() method to save the selected video.

python
# Download the selected stream
output_path = selected_stream.download()
print(f"Video downloaded successfully to: {output_path}")

Step 5: Add Audio-Only Download Option

Include an option for downloading audio files.

python
# Display available audio streams
audio_streams = yt.streams.filter(only_audio=True)
print("\nAvailable Audio Streams:")
for i, stream in enumerate(audio_streams):
print(f"{i + 1}. Bitrate: {stream.abr}, File Type: {stream.mime_type}")
# Let the user choose an audio stream
audio_choice = int(input(“Enter the number for audio download (or 0 to skip): “))
if audio_choice > 0:
selected_audio = audio_streams[audio_choice – 1] audio_path = selected_audio.download()
print(f”Audio downloaded successfully to: {audio_path})

Complete Code

Here’s the final implementation:

python

from pytube import YouTube

def download_video():
try:
# Get video URL
video_url = input(“Enter the YouTube video URL: “)
yt = YouTube(video_url)

# Display video details
print(f”\nTitle: {yt.title})
print(f”Views: {yt.views})

# Show available video streams
streams = yt.streams.filter(progressive=True)
print(“\nAvailable Video Streams:”)
for i, stream in enumerate(streams):
print(f”{i + 1}. Resolution: {stream.resolution}, File Type: {stream.mime_type})

# User selects a video stream
choice = int(input(“Enter the number of your choice for video download: “)) – 1
selected_stream = streams[choice]

# Download video
output_path = selected_stream.download()
print(f”Video downloaded successfully to: {output_path})

# Show available audio streams
audio_streams = yt.streams.filter(only_audio=True)
print(“\nAvailable Audio Streams:”)
for i, stream in enumerate(audio_streams):
print(f”{i + 1}. Bitrate: {stream.abr}, File Type: {stream.mime_type})

# User selects an audio stream
audio_choice = int(input(“Enter the number for audio download (or 0 to skip): “))
if audio_choice > 0:
selected_audio = audio_streams[audio_choice – 1] audio_path = selected_audio.download()
print(f”Audio downloaded successfully to: {audio_path})

except Exception as e:
print(f”Error: {e})

if __name__ == “__main__”:
download_video()


Enhancements

  1. Download Folder: Allow users to specify a folder for downloads using output_path.
  2. Progress Bar: Integrate a progress bar to show download progress using the tqdm library.
  3. Batch Downloader: Enable downloading multiple videos from a list of URLs.
  4. GUI Application: Use tkinter or PyQt to build a graphical interface for non-technical users.
  5. Error Handling: Improve handling of invalid URLs or connectivity issues.

Sample Output

plaintext

Enter the YouTube video URL: https://www.youtube.com/watch?v=dQw4w9WgXcQ

Title: Never Gonna Give You Up
Views: 1,234,567

Available Video Streams:
1. Resolution: 360p, File Type: video/mp4
2. Resolution: 720p, File Type: video/mp4

Enter the number of your choice for video download: 2
Video downloaded successfully to: ./Never_Gonna_Give_You_Up.mp4

Available Audio Streams:
1. Bitrate: 128kbps, File Type: audio/mp4

Enter the number for audio download (or 0 to skip): 1
Audio downloaded successfully to: ./Never_Gonna_Give_You_Up_audio.mp4