OdinSchool OdinSchool
Top 15 Python Projects for 2024 - Code Available

Top 15 Python Projects for 2024 - Code Available

Summary

Python plays a critical role in scientific computing, machine learning, and data analysis, making it indispensable for data science experts. Its widespread adoption and continuous growth underscore its importance. Learning Python is an ongoing process, with practice through projects being essential. Hence, this blog has projects for every level. These hands-on experiences are invaluable for solidifying Python skills and achieving proficiency.

Scientific computing, machine learning, and data analysis all heavily rely on Python, making it an essential tool for data science experts. 

Python remains the second most-used programming language on GitHub. Interestingly, Python's use grew more than 22% year over year, with more than four million developers on GitHub. source

The process of improving your Python programming abilities never ends, regardless of your level of experience. Hence, its important to join a comprehensive data science course whose curriculum is always updated as per the industry standards.

The best example would be that of Sourav Karmakar, who used his bench time at TCS to practice Python, and here he is, a successful data scientist with Tiger Analytics, drawing almost 6 times the salary he used to get before the transition.

OdinGrad | Sourav-Karmakar

This article will help you practice more by providing code along with the top Python projects.

Beginner-level Python Projects

#1. Personal Budget Manager

A command-line application to manage your personal finances. You can add expenses and income, categorize them, and see summaries of your financial activities.

import json

def load_transactions():
    try:
        with open('transactions.json', 'r') as file:
            return json.load(file)
    except FileNotFoundError:
        return []

def save_transactions(transactions):
    with open('transactions.json', 'w') as file:
        json.dump(transactions, file, indent=4)

def add_transaction(transactions, type, amount, category):
    transactions.append({"type": type, "amount": amount, "category": category})
    save_transactions(transactions)

def show_summary(transactions):
    income = sum(t['amount'] for t in transactions if t['type'] == 'income')
    expense = sum(t['amount'] for t in transactions if t['type'] == 'expense')
    balance = income - expense
    print(f"Total Income: {income}, Total Expense: {expense}, Balance: {balance}")

transactions = load_transactions()

# Example usage
add_transaction(transactions, 'income', 500, 'salary')
add_transaction(transactions, 'expense', 100, 'groceries')
show_summary(transactions)

#2. Simple Chatbot

A simple chatbot that can perform basic interactions with the user, using predefined responses to simulate conversation.

def chatbot_response(message):
    message = message.lower()
    if "hello" in message:
        return "Hello there! How can I help you?"
    elif "how are you" in message:
        return "I'm a bot, so I'm always doing well, thanks!"
    elif "bye" in message:
        return "Goodbye! Have a nice day!"
    else:
        return "I'm not sure how to respond to that. Can you ask something else?"

# Example interaction with the chatbot
user_message = input("You: ")
print("Bot:", chatbot_response(user_message))

#3. Email Slicer

An application that takes an email address and extracts the username and domain name.

Key Concepts Covered

  1. String manipulation and methods

  2. Working with user input

def email_slicer(email):
    username, domain = email.split('@')
    return username, domain

email = input("Enter your email: ").strip()
username, domain = email_slicer(email)
print(f"Username: {username}, Domain: {domain}")

 

#4. Desktop Notifier App

A desktop notifier app that sends you a notification at scheduled intervals.

Key Concepts Covered

  1. Working with external libraries (plyer)

  2. Scheduling tasks

from plyer import notification
import time

def send_notification(title, message):
    notification.notify(
        title=title,
        message=message,
        timeout=10
    )

while True:
    # Send a notification every hour
    send_notification("Reminder", "Stretch your legs! It's been an hour.")
    time.sleep(3600)  # Sleep for 1 hour

#5. Currency Converter

A simple currency converter that uses an API to fetch the latest exchange rates and perform currency conversion.

Key Concepts Covered
  1. API requests

  2. Handling JSON data

  3. User input and error handling

import requests

def convert_currency(amount, from_currency, to_currency, api_key):
    url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
    response = requests.get(url)
    data = response.json()
    rates = data['rates']
    converted_amount = amount * rates[to_currency]
    return converted_amount

# Example usage (You'll need a valid API key)
amount = 100
from_currency = 'USD'
to_currency = 'EUR'
api_key = 'YOUR_API_KEY_HERE'
print(f"{amount} {from_currency} is equal to {convert_currency(amount, from_currency, to_currency, api_key)} {to_currency}")

Steps to get API key

  1. Visit the ExchangeRate-API website: Go to the ExchangeRate-API website.

  2. Sign Up for an Account: You will need to sign up for an account by providing your email address and creating a password. ExchangeRate-API usually offers a free tier, which might be sufficient for basic usage or testing purposes.

  3. Get Your API Key: After signing up, you will be given an API key. This is a unique identifier that allows you to make requests to their service.

  4. Use Your API Key in the Code: Replace 'YOUR_API_KEY_HERE' in your code with the actual API key you received. Note, however, that your current code snippet does not utilize the api_key variable in the request. To properly use the API key, you'll likely need to adjust your code according to the API's documentation, as some APIs require the key to be included in the request headers or as a query parameter.

#6. Simple File Organizer

A script that organizes files in a directory into subdirectories based on file type.
Key Concepts Covered

  1. File and directory operations

  2. Working with paths

  3. Automating routine tasks

import os
from pathlib import Path

def organize_directory(path):
    for item in os.listdir(path):
        item_path = Path(path) / item
        if item_path.is_file():
            file_type = item.split('.')[-1]
            directory = Path(path) / file_type
            directory.mkdir(exist_ok=True)
            item_path.rename(directory / item)

# Example usage
organize_directory('path/to/your/directory')

He found Python much easier to learn when compared to other languages. Shubham explored further and learnt different Python tools like Pandas, Numpy, etc. At this stage, he wanted a certification in it.

OdinGrad - Shubham success story

Python Projects for Intermediate Level

#1. Real-time Face Recognition System

Develop a Python application that can identify and label faces in a video stream in real-time.

import face_recognition

import cv2

import numpy as np

# Load a sample picture and learn how to recognize it.

your_image = face_recognition.load_image_file("your_image.jpg")

your_face_encoding = face_recognition.face_encodings(your_image)[0]

# Create arrays of known face encodings and their names

known_face_encodings = [your_face_encoding]

known_face_names = ["Your Name"]

# Initialize some variables

face_locations = []

face_encodings = []

face_names = []

process_this_frame = True

# Capture video from the first webcam

video_capture = cv2.VideoCapture(0)

while True:

    # Grab a single frame of video

    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing

    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)

    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time

    if process_this_frame:

        # Find all the faces and face encodings in the current frame of video

        face_locations = face_recognition.face_locations(rgb_small_frame)

        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []

        for face_encoding in face_encodings:

            # See if the face is a match for the known face(s)

            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)

            name = "Unknown"

            # Use the known face with the smallest distance to the new face

            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)

            best_match_index = np.argmin(face_distances)

            if matches[best_match_index]:

                name = known_face_names[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results

    for (top, right, bottom, left), name in zip(face_locations, face_names):

        # Scale back up face locations since the frame we detected in was scaled to 1/4 size

        top *= 4

        right *= 4

        bottom *= 4

        left *= 4

        # Draw a box around the face

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)

        # Draw a label with a name below the face

        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)

        font = cv2.FONT_HERSHEY_DUPLEX

        cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)

    # Display the resulting image

    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break

# Release handle to the webcam

video_capture.release()

cv2.destroyAllWindows()

 

#2. Sentiment Analysis Tool

The goal of this project is to create a Python application that can determine the sentiment of a given piece of text. The application will analyze text inputs (such as sentences, paragraphs, or entire documents) and classify the sentiment as positive, negative, or neutral.

Skills Developed:

  1. Natural Language Processing (NLP): Learn the basics of NLP, including how to work with textual data, tokenize words, and analyze sentiment.

  2. Data Analysis: Practice handling and processing data, potentially working with large datasets of text.

  3. Libraries and APIs: Gain experience with Python libraries like textblob and pandas, and learn how to leverage them for sentiment analysis and data manipulation.

from textblob import TextBlob

# Example text
text = "Python is amazing, but learning it can be challenging."

# Analyze sentiment
blob = TextBlob(text)
print(blob.sentiment)
# Output: Sentiment(polarity=0.21666666666666667, subjectivity=0.5833333333333334)

# For a dataset, read using pandas and apply sentiment analysis on each row
# df = pd.read_csv('your_dataset.csv')
# df['sentiment'] = df['text_column'].apply(lambda x: TextBlob(x).sentiment.polarity)

#3. Custom Command-Line Tool

Develop a versatile command-line tool for a specific task, such as batch processing files, text manipulation, or generating reports from datasets. This tool will accept various command-line arguments to perform its functions dynamically.

Skills Developed:

  1. Command-Line Interface (CLI) Design: Learn how to design and implement a user-friendly CLI, including parsing command-line arguments and providing useful feedback to users.

  2. File and Data Processing: Enhance your skills in reading from and writing to files, as well as performing operations on data (e.g., filtering, sorting, transforming).

  3. Automation: Understand how to automate repetitive tasks, improving efficiency and productivity.

import sys

def process_command(command):
    # Example functionality: print reversed command
    print(command[::-1])

if __name__ == "__main__":
    if len(sys.argv) > 1:
        process_command(sys.argv[1])
    else:
        print("Please provide a command.")

#4. Image Manipulation Tool

Create a script that allows users to apply modifications to images, such as applying filters, resizing, cropping, or adjusting colors. This tool will provide a simple interface for image editing without the need for complex software.

Skills Developed:

  1. Image Processing: Learn the fundamentals of image processing, including working with pixels, applying filters, and modifying image properties.

  2. Pillow Library: Get hands-on experience with the Pillow library, a powerful tool for opening, manipulating, and saving many different image file formats.

  3. Creative Coding: Explore the creative aspects of coding by developing algorithms to enhance and manipulate images.

from PIL import Image, ImageFilter

# Open an image
image = Image.open('your_image.jpg')

# Apply a filter
blurred_image = image.filter(ImageFilter.BLUR)

# Save the modified image
blurred_image.save('blurred_output.jpg')

# Resize and crop
image.thumbnail((100, 100)) # Resize maintaining aspect ratio
image.save('resized_output.jpg')

#5. Weather CLI Application

Build a command-line application that fetches weather information from an external API and displays it to the user. The app will allow users to input a location (e.g., city name) and retrieve current weather data, such as temperature, humidity, and weather conditions.

Skills Developed:

  1. Working with APIs: Learn how to make HTTP requests to external APIs, handle responses, and parse JSON data.

  2. Data Presentation: Improve your skills in processing and presenting data in a user-friendly manner through the command line.

  3. Networking Concepts: Gain a basic understanding of networking concepts, including HTTP requests, API keys, and rate limiting.

import requests

API_KEY = 'your_api_key_here'
BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"

def get_weather(city_name):
    url = BASE_URL + "appid=" + API_KEY + "&q=" + city_name
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        weather = data['weather'][0]['description']
        temperature = round(data['main']['temp'] - 273.15, 2) # Convert from Kelvin to Celsius
        print(f"Weather: {weather}")
        print(f"Temperature: {temperature}°C")
    else:
        print("Error fetching weather data")

if __name__ == "__main__":
    city_name = input("Enter city name: ")
    get_weather(city_name)

Ned Batchelder, a software engineer, used Python to create "Nat's World," a virtual environment for his autistic son, Nat. 

Steps to get API Keys

  1. Visit the OpenWeatherMap website: Go to OpenWeatherMap and look for the API section, or directly navigate to their API page.

  2. Sign Up/Register: If you don’t already have an account, you'll need to sign up by providing your details. OpenWeatherMap offers a free tier, which is usually sufficient for basic usage and personal projects.

  3. Subscribe to an API Plan: After signing up, subscribe to an API plan. The free plan should be enough to get started with basic weather data fetching. If its asking for payment details, then go to 'My API Keys' under your name at the top right.

  4. Get Your API Key: Once you've subscribed to a plan, you'll be able to access your API key, which is required to make requests to their API endpoints.

  5. Use your API key in the code: Replace 'your_api_key_here' in your code with the actual API key you received. Ensure the API key is correctly inserted into the API_KEY variable.

Python Projects for Advanced

#1. Real-time Object Detection System using OpenCV and YOLO

This Python code snippet demonstrates how to implement a real-time object detection system using the OpenCV library in conjunction with a pre-trained YOLO (You Only Look Once) model.

The system captures video frames from a webcam, processes each frame to detect objects using the YOLO algorithm, and then draws bounding boxes around detected objects with their class names and confidence scores.

This method is widely used in various applications, including surveillance, vehicle detection in traffic, and analyzing retail environments for customer behavior.

import cv2
import numpy as np

# Load YOLO
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]

layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

# Loading image
cap = cv2.VideoCapture(0)  # Use 0 for web camera

while True:
    _, frame = cap.read()
    height, width, channels = frame.shape

    # Detecting objects
    blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
    net.setInput(blob)
    outs = net.forward(output_layers)

    # Showing informations on the screen
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.5:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # Rectangle coordinates
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

                cv2.putText(frame, f"{classes[class_id]} {int(confidence * 100)}%", 
                            (x, y + 30), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 2)
                
    cv2.imshow("Image", frame)
    key = cv2.waitKey(1)
    if key == 27:  # ESC key to break
        break

cap.release()
cv2.destroyAllWindows()

#2. Automated Trading Bot (Simulation Example)

This simplified Python example outlines the basic structure for simulating an automated trading strategy. The script simulates a scenario where a bot trades based on simple price movement rules: it buys when the price increases by more than 1% from the previous day and sells when the price decreases by more than 1%.

This simulation provides a framework for understanding how trading bots analyze price data and make decisions, although real-world applications require much more sophisticated analysis and risk management strategies.

import numpy as np
import pandas as pd

def simulate_trading_strategy(prices):
    """
    This function simulates a simple trading strategy where it buys when the price
    increases by more than 1% from the previous day and sells when it decreases by more than 1%.
    """
    cash = 10000  # Starting cash
    shares = 0  # Starting shares
    buy_threshold = 1.01  # 1% increase
    sell_threshold = 0.99  # 1% decrease

    for i in range(1, len(prices)):
        if prices[i] / prices[i-1] > buy_threshold and cash > 0:
            shares = cash / prices[i]
            cash = 0
            print(f"Bought at {prices[i]}")
        elif prices[i] / prices[i-1] < sell_threshold and shares > 0:
            cash = shares * prices[i]
            shares = 0
            print(f"Sold at {prices[i]}")
    
    # Final value if we have shares then sell them at the last price
    final_value = cash + (shares * prices[-1])
    return final_value

# Example price data (could be replaced with real data)
prices = np.random.random(100) * 100  # Simulated stock prices

final_value = simulate_trading_strategy(prices)
print(f"Final Portfolio Value: {final_value}")


#3. Advanced Web Scraping and Data Analysis

Create a sophisticated web scraping tool using frameworks like Scrapy or BeautifulSoup to extract data from complex websites. Combine the scraped data with powerful data analysis libraries like pandas, NumPy, or seaborn to gain insights and visualize patterns from the collected data.

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('span small::text').get(),
                'tags': quote.css('div.tags a.tag::text').getall(),
            }

        next_page = response.css('li.next a::attr(href)').get()
        if next_page is not None:
            yield response.follow(next_page, self.parse)

#4. Generative Adversarial Networks (GANs) for Image Generation

Description: Implement a Generative Adversarial Network (GAN) to generate realistic images from random noise. Experiment with different architectures such as DCGAN, WGAN, or StyleGAN. Train the GAN on large datasets like CelebA or CIFAR-10 to produce high-quality images.

import tensorflow as tf
from tensorflow.keras import layers, models

# Define generator model
def build_generator(latent_dim):
    model = models.Sequential([
        layers.Dense(7*7*256, input_dim=latent_dim),
        layers.Reshape((7, 7, 256)),
        layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same', activation='relu'),
        layers.Conv2DTranspose(64, (4, 4), strides=(2, 2), padding='same', activation='relu'),
        layers.Conv2DTranspose(1, (7, 7), activation='sigmoid', padding='same')
    ])
    return model

# Define discriminator model
def build_discriminator(input_shape):
    model = models.Sequential([
        layers.Conv2D(64, (3, 3), strides=(2, 2), padding='same', input_shape=input_shape),
        layers.LeakyReLU(alpha=0.2),
        layers.Dropout(0.4),
        layers.Conv2D(128, (3, 3), strides=(2, 2), padding='same'),
        layers.LeakyReLU(alpha=0.2),
        layers.Dropout(0.4),
        layers.Flatten(),
        layers.Dense(1, activation='sigmoid')
    ])
    return model

# Define GAN model
def build_gan(generator, discriminator):
    discriminator.trainable = False
    model = models.Sequential([
        generator,
        discriminator
    ])
    return model

#5. Deep Reinforcement Learning for Autonomous Vehicles

Develop a deep reinforcement learning (DRL) model to enable autonomous vehicles to navigate complex environments and perform tasks such as lane following, obstacle avoidance, and decision making at intersections. 
import gym
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models, optimizers

env = gym.make("CartPole-v1")

num_actions = env.action_space.n

model = models.Sequential([
    layers.Dense(24, input_shape=(4,), activation='relu'),
    layers.Dense(24, activation='relu'),
    layers.Dense(num_actions, activation='linear')
])

model.compile(optimizer=optimizers.Adam(), loss='mse')

def choose_action(state, epsilon):
    if np.random.rand() <= epsilon:
        return env.action_space.sample()
    return np.argmax(model.predict(state))

def replay(memory, batch_size, gamma):
    minibatch = random.sample(memory, batch_size)
    for state, action, reward, next_state, done in minibatch:
        target = reward
        if not done:
            target = reward + gamma * np.amax(model.predict(next_state)[0])
        target_f = model.predict(state)
        target_f[0][action] = target
        model.fit(state, target_f, epochs=1, verbose=0)

Conclusion

Overall, this collection of Python projects offers something for everyone, regardless of their skill level or areas of interest. By working through these projects, learners can not only strengthen their Python programming skills but also gain practical experience in building real-world applications and exploring emerging technologies.

If you want to practice more then here are some more projects for you,

Python Practice

 

Whether you're a beginner looking to get started or an advanced developer seeking new challenges, there's a project here for you to explore and expand your Python expertise.

And, here are the top 50 python interview questions with answers

Frequently Asked Questions about Python

DEBIT CARD | Awook Org

Q1 - Why should I learn python?

Because, Python skills are in high demand across various industries, including software development, data science, machine learning, web development, and automation. Proficiency in Python can open doors to a wide range of job opportunities

Q2 - How long does it take to learn Python fully?

The time it takes to fully learn Python varies depending on factors such as your prior programming experience, the depth of knowledge you aim to achieve, and how much time you dedicate to learning. However, many beginners can gain proficiency in Python basics within a few weeks to a few months of consistent practice and study.

Q3 - What are the job prospects for Python developers?

Python developers are in high demand across industries, including software development, data science, machine learning, web development, and automation. Job roles include software engineer, data scientist, machine learning engineer, web developer, and more.

Q4 - How is Python when compared to other programming languages?

Python is often compared to languages like Java, JavaScript, and C++. While each language has its strengths and use cases, Python's simplicity, versatility, and extensive libraries make it a popular choice for a wide range of applications.

Share

About the Author

Mechanical engineer turned wordsmith, Pratyusha, holds an MSIT from IIIT, seamlessly blending technical prowess with creative flair in her content writing. By day, she navigates complex topics with precision; by night, she's a mom on a mission, juggling bedtime stories and brainstorming sessions with equal delight.

Join OdinSchool's Data Science Bootcamp

With Job Assistance

View Course