Top 10 Python Projects with source code [2025]
![Top 10 Python Projects with source code [2025]](/blog/content/images/size/w2000/2024/12/Artboard-1@2x--1-.png)
Introduction
Python is one of the most versatile and beginner-friendly programming languages, making it a favorite choice for developers worldwide.
Whether you’re just starting or an experienced programmer, working on real-world projects is the best way to sharpen your skills.
This blog will explore 10 exciting Python projects with source code to help you enhance your coding abilities. These projects cover a range of domains like data science, web development, automation, and more, providing ample opportunities to learn and grow.
Best Python Projects with Source Code in 2025 - Beginner to Advanced
With almost 8.2 million users globally, Python has found one of the most widespread uses across various applications and domains. After mastering the language, asses your skills in real-world scenarios by working on the following projects.
1. Number Guessing Game
A Number Guessing Game is a simple project perfect for beginners, where the program randomly generates a number within a specified range, and the user has to guess it.
You will use Python's random library to generate the number and input() for user interaction. The program should provide hints like "Too High" or "Too Low" after each guess, and it should terminate once the user guesses correctly or exceeds a set number of attempts.
This project helps solidify your understanding of loops, conditionals, and basic I/O in Python, with the desired outcome being a functional guessing game that tracks user guesses.
Source Code
import random
def number_guessing_game():
print("Welcome to the Number Guessing Game!")
number_to_guess = random.randint(1, 100)
attempts = 0
max_attempts = 10
print("I'm thinking of a number between 1 and 100.")
print(f"You have {max_attempts} attempts to guess it.")
while attempts < max_attempts:
try:
guess = int(input(f"Attempt {attempts + 1}: Enter your guess: "))
attempts += 1
if guess == number_to_guess:
print(f"Congratulations! You guessed the number {number_to_guess} in {attempts} attempts!")
break
elif guess < number_to_guess:
print("Too low! Try again.")
else:
print("Too high! Try again.")
except ValueError:
print("Invalid input. Please enter a number.")
if attempts == max_attempts and guess != number_to_guess:
print(f"Sorry, you've used all your attempts. The number was {number_to_guess}. Better luck next time!")
if __name__ == "__main__":
number_guessing_game()
2. To-Do List App
A To-Do List App is a great project to manage tasks directly from the command line, allowing users to add, delete, view, and mark tasks as completed.
You can use Python’s sqlite3 library to create a database for storing tasks persistently or use a plain text file for a simpler version.
The app involves creating CRUD (Create, Read, Update, Delete) operations, providing an interactive menu for task management. This project introduces database handling or file I/O concepts, with the desired outcome being a robust task management tool that runs on the terminal.
Source Code
import sqlite3
# Create the tasks table
def create_table():
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'Pending'
)""")
conn.commit()
conn.close()
# Add a new task to the list
def add_task(task):
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO tasks (task) VALUES (?)", (task,))
conn.commit()
conn.close()
print("Task added successfully!")
# View all tasks in the list
def view_tasks():
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM tasks")
tasks = cursor.fetchall()
conn.close()
if tasks:
print("\nYour To-Do List:")
for task in tasks:
print(f"ID: {task[0]} | Task: {task[1]} | Status: {task[2]}")
else:
print("No tasks found!")
# Delete a task by ID
def delete_task(task_id):
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
conn.commit()
conn.close()
print("Task deleted successfully!")
# Mark a task as completed by ID
def mark_task_complete(task_id):
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("UPDATE tasks SET status = 'Completed' WHERE id = ?", (task_id,))
conn.commit()
conn.close()
print("Task marked as completed!")
# Main application loop
def main():
create_table()
while True:
print("\nTo-Do List App")
print("1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Mark Task as Completed")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
task = input("Enter the task: ")
add_task(task)
elif choice == "2":
view_tasks()
elif choice == "3":
task_id = input("Enter the task ID to delete: ")
if task_id.isdigit():
delete_task(int(task_id))
else:
print("Invalid ID!")
elif choice == "4":
task_id = input("Enter the task ID to mark as completed: ")
if task_id.isdigit():
mark_task_complete(int(task_id))
else:
print("Invalid ID!")
elif choice == "5":
print("Exiting the app. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
3. Rock, Paper, Scissors Game
The Rock, Paper, Scissors Game is a fun interactive project where the user competes against the computer in a classic game.
The program allows the user to input their choice (rock, paper, or scissors) while the computer makes a random choice using Python's random module. The rules are straightforward: rock beats scissors, scissors beat paper, and paper beats rock.
This project helps reinforce the use of loops, conditionals, and randomness in Python, with the desired outcome being a fully functional game where the user can play multiple rounds and see the results.
Source Code
import random
def get_computer_choice():
choices = ["rock", "paper", "scissors"]
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "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"):
return "You win!"
else:
return "Computer wins!"
def rock_paper_scissors():
print("Welcome to Rock, Paper, Scissors!")
while True:
user_choice = input("\nEnter your choice (rock, paper, scissors): ").lower()
if user_choice not in ["rock", "paper", "scissors"]:
print("Invalid choice. Please try again.")
continue
computer_choice = get_computer_choice()
print(f"Computer chose: {computer_choice}")
result = determine_winner(user_choice, computer_choice)
print(result)
play_again = input("\nDo you want to play again? (yes/no): ").lower()
if play_again != "yes":
print("Thanks for playing! Goodbye!")
break
if __name__ == "__main__":
rock_paper_scissors()
4. Calculator
Based on user input, the Basic Calculator project is designed to perform arithmetic operations such as addition, subtraction, multiplication, and division. It allows the user to instantly choose an operation, input numbers, and receive results.
This project demonstrates using functions, conditionals, and user input validation in Python. You’ll also implement error handling to manage scenarios like division by zero.
The desired outcome is a functional command-line calculator with an intuitive menu for operation selection.
Source Code
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: Division by zero is not allowed."
def calculator():
print("Welcome to the Basic Calculator!")
while True:
print("\nSelect an operation:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Exit")
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == "5":
print("Thank you for using the calculator. Goodbye!")
break
if choice in ["1", "2", "3", "4"]:
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
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)}")
except ValueError:
print("Invalid input. Please enter numeric values.")
else:
print("Invalid choice. Please select a valid operation.")
if __name__ == "__main__":
calculator()
5. Password Generator
The Password Generator is a handy utility tool that creates strong, secure passwords based on user-defined criteria, such as length and includes uppercase letters, numbers, and special characters.
It uses Python's random and string libraries to generate random combinations of characters, ensuring high security.
This project teaches you about string manipulation and randomness while providing a practical tool. The desired outcome is a script that outputs secure passwords to suit various user preferences.
Source Code
import random
import string
def generate_password(length, include_uppercase, include_numbers, include_special_chars):
lower = string.ascii_lowercase
upper = string.ascii_uppercase if include_uppercase else ''
numbers = string.digits if include_numbers else ''
special_chars = string.punctuation if include_special_chars else ''
all_chars = lower + upper + numbers + special_chars
if not all_chars:
return "Error: At least one character set must be selected!"
password = ''.join(random.choice(all_chars) for _ in range(length))
return password
def password_generator():
print("Welcome to the Password Generator!")
try:
length = int(input("Enter the desired password length: "))
if length <= 0:
print("Password length must be greater than 0.")
return
include_uppercase = input("Include uppercase letters? (yes/no): ").lower() == 'yes'
include_numbers = input("Include numbers? (yes/no): ").lower() == 'yes'
include_special_chars = input("Include special characters? (yes/no): ").lower() == 'yes'
password = generate_password(length, include_uppercase, include_numbers, include_special_chars)
print(f"\nYour generated password is: {password}")
except ValueError:
print("Invalid input. Please enter a numeric value for length.")
if __name__ == "__main__":
password_generator()
6. Chatbot
A Chatbot is an interactive application that can answer basic user queries. It simulates a conversation with the user using predefined responses.
This chatbot can be built using Python's basic conditionals and loops to simulate a conversation. The chatbot can respond to questions such as "Hello," "How are you?" and "What is your name?" and can be extended to handle more sophisticated conversations.
The project will give you experience in handling user input and controlling program flow through decision structures. The desired outcome is a basic chatbot that can hold a simple conversation with the user.
Source Code
def chatbot():
print("Hello! I am your chatbot. Type 'quit' to exit.")
while True:
user_input = input("You: ").lower()
if user_input == 'quit':
print("Goodbye! Have a great day!")
break
elif 'hello' in user_input or 'hi' in user_input:
print("Chatbot: Hello! How can I assist you today?")
elif 'how are you' in user_input:
print("Chatbot: I'm doing great, thank you for asking!")
elif 'your name' in user_input:
print("Chatbot: I am a chatbot created to assist you.")
elif 'bye' in user_input:
print("Chatbot: Goodbye! It was nice talking to you!")
break
else:
print("Chatbot: I'm sorry, I didn't understand that. Can you ask something else?")
if __name__ == "__main__":
chatbot()
7. Weather Forecast Application
The Weather Forecast Application lets users get real-time weather information for any city using a public API (such as OpenWeatherMap).
This project is a good exercise in working with APIs and JSON data and handling user input to display real-time information.
The user enters the name of a city, and the program fetches the weather data for that city, including temperature, humidity, weather conditions, etc. This project also introduces error handling for cases when the city is not found or the API request fails.
Source Code
import requests
def get_weather(city):
# Replace 'your_api_key' with your actual OpenWeatherMap API key
api_key = "your_api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city}&appid={api_key}&units=metric"
response = requests.get(complete_url)
data = response.json()
if data["cod"] != "404":
main_data = data["main"]
weather_data = data["weather"][0]
city_name = data["name"]
temp = main_data["temp"]
pressure = main_data["pressure"]
humidity = main_data["humidity"]
weather_desc = weather_data["description"]
print(f"Weather in {city_name}:")
print(f"Temperature: {temp}°C")
print(f"Pressure: {pressure} hPa")
print(f"Humidity: {humidity}%")
print(f"Weather: {weather_desc.capitalize()}")
else:
print("City not found!")
def weather_app():
print("Welcome to the Weather Forecast Application!")
while True:
city = input("\nEnter a city name (or type 'exit' to quit): ").strip()
if city.lower() == 'exit':
print("Goodbye!")
break
get_weather(city)
if __name__ == "__main__":
weather_app()
8. Stock Price Tracker
The Stock Price Tracker project allows users to get real-time stock prices for any company using an external API. This project requires you to interact with an API such as Alpha Vantage or Yahoo Finance to fetch live stock price data.
The program will allow the user to enter a stock ticker (e.g., "AAPL" for Apple or "GOOGL" for Google) and display the latest stock price.
It’s an excellent project for practising working with APIs, parsing JSON data, and scheduling periodic checks for stock updates. The desired outcome is a fully functional stock price tracker that provides real-time data to the user.
Source Code
import requests
import time
# Function to get the stock price
def get_stock_price(ticker):
api_key = "your_api_key" # Replace with your Alpha Vantage API key
url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker}&interval=5min&apikey={api_key}"
response = requests.get(url)
data = response.json()
if "Time Series (5min)" in data:
time_series = data["Time Series (5min)"]
latest_time = next(iter(time_series)) # Get the latest time
latest_data = time_series[latest_time]
price = latest_data["4. close"] # Get the closing price at the latest time
print(f"Stock: {ticker}\nPrice: ${price}\nTime: {latest_time}")
else:
print("Error: Unable to retrieve stock data or invalid ticker.")
# Function to track the stock
def stock_tracker():
print("Welcome to the Stock Price Tracker!")
while True:
ticker = input("\nEnter a stock ticker (or type 'exit' to quit): ").upper().strip()
if ticker.lower() == 'exit':
print("Goodbye!")
break
get_stock_price(ticker)
# Wait for a minute before the next check
time.sleep(60)
if __name__ == "__main__":
stock_tracker()
9. Image Recognition with OpenCV & TensorFlow
The Image Recognition Project uses machine learning models to classify images into predefined categories.
You can create an advanced image recognition system by combining OpenCV for image processing and TensorFlow (or Keras) for building and using machine learning models. This project involves setting up a pre-trained model (like MobileNet or ResNet) and using it to classify images.
You can also expand it to work with your dataset for custom classification tasks. The desired outcome is a program that can take an image as input and return the predicted class or label.
Source Code
import cv2
import numpy as np
import tensorflow as tf
# Load the pre-trained MobileNetV2 model
model = tf.keras.applications.MobileNetV2(weights='imagenet')
# Define the preprocessing function for the image
def preprocess_image(image_path):
# Load image with OpenCV
img = cv2.imread(image_path)
# Convert the image to RGB as OpenCV uses BGR
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Resize the image to 224x224 as expected by MobileNetV2
img = cv2.resize(img, (224, 224))
# Preprocess image for MobileNetV2
img = tf.keras.applications.mobilenet_v2.preprocess_input(img)
# Expand dimensions to match the model's input shape
img = np.expand_dims(img, axis=0)
return img
# Function to predict the class of an image
def predict_image(image_path):
img = preprocess_image(image_path)
# Get the predictions from the model
predictions = model.predict(img)
# Decode the predictions to human-readable labels
decoded_predictions = tf.keras.applications.mobilenet_v2.decode_predictions(predictions, top=1)[0]
# Print the predicted class and confidence score
print(f"Predicted class: {decoded_predictions[0][1]}")
print(f"Confidence score: {decoded_predictions[0][2]*100:.2f}%")
# Main function to run the image recognition
def image_recognition():
print("Welcome to the Image Recognition system!")
# Get the image file path from the user
image_path = input("Enter the path of the image: ")
# Predict the image class
predict_image(image_path)
if __name__ == "__main__":
image_recognition()
10. AI Chatbot with Deep Learning (NLP)
An AI Chatbot with Deep Learning uses Natural Language Processing (NLP) techniques and deep learning models to understand and respond to user queries more sophisticatedly than simple rule-based chatbots.
In this project, we will use the TensorFlow/Keras library to create a neural network that classifies user input and generates contextually relevant responses.
This chatbot will be based on training data (questions and answers) and use a sequence-to-sequence model or RNN/LSTM (Recurrent Neural Networks) to generate meaningful responses.
The goal is to create a bot that can intelligently interact with users conversationally.
Source Code
First, you must install the required libraries to execute the project.
pip install nltk tensorflow keras numpy scikit-learn
import numpy as np
import nltk
import tensorflow as tf
from nltk.stem import WordNetLemmatizer
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.optimizers import Adam
# Initialize the Lemmatizer
lemmatizer = WordNetLemmatizer()
# Example intents (usually, you would load this from a JSON or database)
intents = {
"intents": [
{"tag": "greeting", "patterns": ["Hi", "Hello", "Hey", "How are you?", "Good morning"], "responses": ["Hello!", "Hi there!", "Good morning!"]},
{"tag": "goodbye", "patterns": ["Bye", "Goodbye", "See you later"], "responses": ["Goodbye!", "Take care!", "See you later!"]},
{"tag": "thanks", "patterns": ["Thank you", "Thanks", "Appreciate it"], "responses": ["You're welcome!", "Happy to help!", "Anytime!"]},
{"tag": "age", "patterns": ["How old are you?", "What's your age?", "How old is the bot?"], "responses": ["I am just a few months old!", "I'm ageless, just a bot!"]},
]
}
# Preprocess the data
words = []
classes = []
documents = []
for intent in intents["intents"]:
for pattern in intent["patterns"]:
word_list = nltk.word_tokenize(pattern)
words.extend(word_list)
documents.append((pattern, intent["tag"]))
classes.append(intent["tag"])
# Lemmatize and remove duplicates
words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]
words = sorted(list(set(words)))
# Sort classes and prepare labels
classes = sorted(list(set(classes)))
# Create training data
training_sentences = []
training_labels = []
for doc in documents:
sentence = doc[0]
tag = doc[1]
# Tokenize each word in the sentence
sentence_words = nltk.word_tokenize(sentence)
training_sentences.append(sentence_words)
training_labels.append(classes.index(tag))
# Convert words to a binary matrix (Bag of Words)
training_sentences = [bow(sentence, words) for sentence in training_sentences]
# Convert labels to categorical values
training_labels = np.array(training_labels)
# Define the model
model = Sequential()
model.add(LSTM(128, input_shape=(len(training_sentences[0]),), activation="relu", return_sequences=True))
model.add(LSTM(128, activation="relu"))
model.add(Dense(64, activation="relu"))
model.add(Dense(len(classes), activation="softmax"))
# Compile the model
model.compile(optimizer=Adam(), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
# Train the model
model.fit(np.array(training_sentences), training_labels, epochs=200, batch_size=5, verbose=1)
# Predict function
def chatbot_response(msg):
# Tokenize and lemmatize the input message
msg_words = nltk.word_tokenize(msg)
msg_words = [lemmatizer.lemmatize(w.lower()) for w in msg_words]
# Convert the message into a bag of words
bow_msg = bow(msg_words, words)
# Predict the intent of the message
prediction = model.predict(np.array([bow_msg]))[0]
intent_index = np.argmax(prediction)
# Get the corresponding tag and response
tag = classes[intent_index]
response = random.choice([i['responses'] for i in intents['intents'] if i['tag'] == tag][0])
return response
# Main chatbot loop
def chat():
print("Bot: Hi! Type 'quit' to exit.")
while True:
msg = input("You: ")
if msg.lower() == 'quit':
print("Bot: Goodbye!")
break
response = chatbot_response(msg)
print(f"Bot: {response}")
if __name__ == "__main__":
chat()