Python Projects for UG Students with Source Code

Python Projects for UG Students with Source Code

Hey there, UG students! So, you’re diving into the world of Python, eh? Python is like that super-friendly buddy who makes coding feel like a breeze. Whether you’re a computer science student, an engineering enthusiast, or just someone curious about programming, Python is your go-to language. It’s simple, it’s powerful, and it’s got a massive community backing it up. In this blog post, we’re going to explore a bunch of Python projects that are perfect for undergraduate students like you. And the best part? We’re including source code for each one, so you can get your hands dirty and start coding right away!

We’ll cover projects ranging from beginner-friendly to intermediate ones, so no matter where you are in your coding journey, there’s something here for you. And don’t worry, so buckle up for a detailed ride through Python projects that’ll help you learn, experiment, and maybe even impress your professors or land that internship!

Python Projects for UG Students with Source Code

Why Python for UG Students?

Before we jump into the projects, let’s talk about why Python is such a big deal. Python is like the paneer tikka of programming languages—versatile, loved by everyone, and easy to work with. Here’s why it’s perfect for undergrads:

  1. Easy to Learn: Python’s syntax is so simple, it feels like writing English. No need to stress about complex rules like in C++ or Java.
  2. Tons of Libraries: From web development to machine learning, Python has libraries like NumPy, Pandas, Flask, and more to make your life easier.
  3. Real-World Applications: Companies like Google, Netflix, and even ISRO use Python. So, learning it gives you a head start in the job market.
  4. Community Support: Stuck on a bug? The Python community on Stack Overflow, Reddit, or even X is always there to help.

Alright, enough chit-chat. Let’s dive into the projects! We’ll start with beginner-level projects and slowly move to intermediate ones. Each project comes with a description, why it’s useful, and the source code. Ready? Let’s go!

Beginner-Level Python Projects

These projects are perfect if you’re just starting with Python. They’ll help you understand the basics like loops, conditionals, functions, and data structures.

Project 1: Simple Calculator

What’s This About?
A calculator is like the “Hello World” of Python projects. It’s simple but teaches you how to take user input, perform calculations, and use conditionals. You can build a basic calculator that does addition, subtraction, multiplication, and division.

Why It’s Cool:

  • You learn how to handle user input.
  • You practice using if-else statements.
  • It’s a great way to understand functions.

Source Code:

def calculator():
    print("Welcome to the Simple Calculator!")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")

    choice = int(input("Enter choice (1-4): "))

    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

    if choice == 1:
        result = num1 + num2
        print(f"{num1} + {num2} = {result}")
    elif choice == 2:
        result = num1 - num2
        print(f"{num1} - {num2} = {result}")
    elif choice == 3:
        result = num1 * num2
        print(f"{num1} * {num2} = {result}")
    elif choice == 4:
        if num2 != 0:
            result = num1 / num2
            print(f"{num1} / {num2} = {result}")
        else:
            print("Error! Division by zero is not allowed.")
    else:
        print("Invalid choice!")

calculator()

How It Works:
This code asks the user to pick an operation (1-4) and input two numbers. Based on the choice, it performs the calculation and displays the result. If the user tries to divide by zero, it shows an error message. Simple, right?

What You Learn:

  • Taking user input with input().
  • Using if-elif-else for decision-making.
  • Basic error handling (like checking for division by zero).

Try This: Add more operations like modulus (%) or power (**). Maybe throw in a loop so the user can keep calculating without restarting the program!

Project 2: Guess the Number Game

What’s This About?
This is a fun game where the computer picks a random number, and the player has to guess it. The program gives hints like “too high” or “too low” to guide the player.

Why It’s Cool:

  • You learn about the random module.
  • It’s a great way to practice loops and conditionals.
  • It’s interactive and fun to play with friends.

Source Code:

import random

def guess_number():
    number = random.randint(1, 100)
    attempts = 0

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

    while True:
        guess = int(input("Enter your guess: "))
        attempts += 1

        if guess < number:
            print("Too low! Try again.")
        elif guess > number:
            print("Too high! Try again.")
        else:
            print(f"Congratulations! You guessed it in {attempts} attempts!")
            break

guess_number()

How It Works:
The program uses random.randint() to pick a number between 1 and 100. The player keeps guessing until they get it right, and the program tracks the number of attempts.

What You Learn:

  • Using the random module.
  • Implementing a while loop.
  • Basic game logic with user interaction.

Try This: Add a limit to the number of guesses or let the user choose the range (like 1-50 or 1-1000). You could also add a “play again” option.

Project 3: To-Do List Manager

What’s This About?
A to-do list app lets you add, view, and delete tasks. It’s like a digital version of your sticky notes, perfect for keeping track of assignments or project deadlines.

Why It’s Cool:

  • You learn about lists and list operations.
  • It introduces file handling (optional) to save tasks.
  • It’s a practical tool you can actually use!

Source Code:

def todo_list():
    tasks = []

    while True:
        print("\nTo-Do List Manager")
        print("1. Add Task")
        print("2. View Tasks")
        print("3. Delete Task")
        print("4. Exit")

        choice = int(input("Enter choice (1-4): "))

        if choice == 1:
            task = input("Enter task: ")
            tasks.append(task)
            print(f"Task '{task}' added!")
        elif choice == 2:
            if tasks:
                print("\nYour Tasks:")
                for i, task in enumerate(tasks, 1):
                    print(f"{i}. {task}")
            else:
                print("No tasks yet!")
        elif choice == 3:
            if tasks:
                print("\nYour Tasks:")
                for i, task in enumerate(tasks, 1):
                    print(f"{i}. {task}")
                task_num = int(input("Enter task number to delete: "))
                if 1 <= task_num <= len(tasks):
                    removed_task = tasks.pop(task_num - 1)
                    print(f"Task '{removed_task}' deleted!")
                else:
                    print("Invalid task number!")
            else:
                print("No tasks to delete!")
        elif choice == 4:
            print("Goodbye!")
            break
        else:
            print("Invalid choice!")

todo_list()

How It Works:
This program uses a list to store tasks. You can add a task, view all tasks, delete a specific task, or exit the program. It uses a while loop to keep the program running until the user chooses to exit.

What You Learn:

  • Working with lists (append, pop, enumerate).
  • Creating a menu-driven program.
  • Handling user input and validating choices.

Try This: Save the tasks to a file using write() and load them back when the program starts using read(). You could also add a feature to mark tasks as completed.

Intermediate-Level Python Projects

Now that you’ve got the basics down, let’s level up with some intermediate projects. These involve libraries, APIs, or more complex logic.

Project 4: Weather App Using API

What’s This About?
This project fetches real-time weather data for any city using an API (Application Programming Interface). You’ll use the requests library to get data from a weather API like OpenWeatherMap.

Why It’s Cool:

  • You learn how to work with APIs, which is super useful for real-world projects.
  • It introduces the requests library and JSON parsing.
  • You get to build something practical you can show off.

Source Code:

import requests

def get_weather():
    api_key = "your_api_key_here"  # Replace with your OpenWeatherMap API key
    city = input("Enter city name: ")
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

    response = requests.get(url)
    data = response.json()

    if data["cod"] == 200:
        weather = data["weather"][0]["description"]
        temp = data["main"]["temp"]
        humidity = data["main"]["humidity"]
        print(f"\nWeather in {city}:")
        print(f"Description: {weather}")
        print(f"Temperature: {temp}°C")
        print(f"Humidity: {humidity}%")
    else:
        print("City not found or API error!")

get_weather()

How It Works:
You need to sign up for a free API key from OpenWeatherMap. The program takes a city name, sends a request to the API, and displays the weather, temperature, and humidity.

What You Learn:

  • Using the requests library to make HTTP requests.
  • Parsing JSON data.
  • Handling API responses and errors.

Try This: Add a loop to check multiple cities or display additional data like wind speed. You could also use a GUI library like tkinter to make it look fancier.

Note: You’ll need to install the requests library using pip install requests and get an API key from OpenWeatherMap.

Project 5: Library Management System

What’s This About?
This project simulates a library where you can add books, view books, issue books, and return them. It’s like running your college library but in code!

Why It’s Cool:

  • You learn about dictionaries and data management.
  • It’s a great way to practice object-oriented programming (OOP).
  • It’s a project you can show in your portfolio.

Source Code:

class Library:
    def __init__(self):
        self.books = {}

    def add_book(self, book_id, title):
        self.books[book_id] = {"title": title, "available": True}
        print(f"Book '{title}' added with ID {book_id}")

    def view_books(self):
        if self.books:
            print("\nAvailable Books:")
            for book_id, details in self.books.items():
                status = "Available" if details["available"] else "Issued"
                print(f"ID: {book_id}, Title: {details['title']}, Status: {status}")
        else:
            print("No books in the library!")

    def issue_book(self, book_id):
        if book_id in self.books:
            if self.books[book_id]["available"]:
                self.books[book_id]["available"] = False
                print(f"Book '{self.books[book_id]['title']}' issued!")
            else:
                print("Book is already issued!")
        else:
            print("Book ID not found!")

    def return_book(self, book_id):
        if book_id in self.books:
            if not self.books[book_id]["available"]:
                self.books[book_id]["available"] = True
                print(f"Book '{self.books[book_id]['title']}' returned!")
            else:
                print("Book is already available!")
        else:
            print("Book ID not found!")

def library_system():
    library = Library()

    while True:
        print("\nLibrary Management System")
        print("1. Add Book")
        print("2. View Books")
        print("3. Issue Book")
        print("4. Return Book")
        print("5. Exit")

        choice = int(input("Enter choice (1-5): "))

        if choice == 1:
            book_id = input("Enter book ID: ")
            title = input("Enter book title: ")
            library.add_book(book_id, title)
        elif choice == 2:
            library.view_books()
        elif choice == 3:
            book_id = input("Enter book ID to issue: ")
            library.issue_book(book_id)
        elif choice == 4:
            book_id = input("Enter book ID to return: ")
            library.return_book(book_id)
        elif choice == 5:
            print("Goodbye!")
            break
        else:
            print("Invalid choice!")

library_system()

How It Works:
The program uses a Library class to manage books stored in a dictionary. Each book has an ID, title, and availability status. You can add, view, issue, or return books.

What You Learn:

  • Object-oriented programming (classes and methods).
  • Using dictionaries for data storage.
  • Building a menu-driven system.

Try This: Add a feature to track who borrowed the book or save the library data to a file. You could also add a search function to find books by title.

Project 6: Simple Snake Game with Pygame

What’s This About?
This is a classic Snake game where the snake eats food to grow longer, and you try to avoid hitting the walls or yourself. We’ll use the pygame library to make it visual.

Why It’s Cool:

  • You learn about game development with pygame.
  • It teaches you about event handling and graphics.
  • It’s super fun to play and show off!

Source Code:

import pygame
import random
import asyncio
import platform

# Initialize Pygame
pygame.init()

# Constants
WIDTH = 800
HEIGHT = 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# Snake class
class Snake:
    def __init__(self):
        self.x = GRID_WIDTH // 2
        self.y = GRID_HEIGHT // 2
        self.direction = "RIGHT"
        self.body = [(self.x, self.y)]
        self.food = self.spawn_food()

    def spawn_food(self):
        while True:
            x = random.randint(0, GRID_WIDTH - 1)
            y = random.randint(0, GRID_HEIGHT - 1)
            if (x, y) not in self.body:
                return x, y

    def move(self):
        if self.direction == "UP":
            self.y -= 1
        elif self.direction == "DOWN":
            self.y += 1
        elif self.direction == "LEFT":
            self.x -= 1
        elif self.direction == "RIGHT":
            self.x += 1

        self.body.insert(0, (self.x, self.y))
        if (self.x, self.y) == self.food:
            self.food = self.spawn_food()
        else:
            self.body.pop()

    def check_collision(self):
        if (self.x < 0 or self.x >= GRID_WIDTH or
            self.y < 0 or self.y >= GRID_HEIGHT or
            (self.x, self.y) in self.body[1:]):
            return True
        return False

# Game setup
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock()
FPS = 10

def setup():
    global snake
    snake = Snake()

def update_loop():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            return
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and snake.direction != "DOWN":
                snake.direction = "UP"
            elif event.key == pygame.K_DOWN and snake.direction != "UP":
                snake.direction = "DOWN"
            elif event.key == pygame.K_LEFT and snake.direction != "RIGHT":
                snake.direction = "LEFT"
            elif event.key == pygame.K_RIGHT and snake.direction != "LEFT":
                snake.direction = "RIGHT"

    snake.move()
    if snake.check_collision():
        print("Game Over!")
        pygame.quit()
        return

    screen.fill((0, 0, 0))
    for x, y in snake.body:
        pygame.draw.rect(screen, GREEN, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    fx, fy = snake.food
    pygame.draw.rect(screen, RED, (fx * GRID_SIZE, fy * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    pygame.display.flip()

async def main():
    setup()
    while True:
        update_loop()
        await asyncio.sleep(1.0 / FPS)

if platform.system() == "Emscripten":
    asyncio.ensure_future(main())
else:
    if __name__ == "__main__":
        asyncio.run(main())

How It Works:
The game uses pygame to create a window where the snake moves based on arrow key inputs. The snake grows when it eats food, and the game ends if it hits the walls or itself.

What You Learn:

  • Using pygame for graphics and event handling.
  • Implementing game logic with classes.
  • Handling asynchronous code for browser compatibility.

Try This: Add a score display, sound effects, or a start/restart screen. You could also increase the speed as the snake grows.

Note: Install pygame using pip install pygame. This code is structured for Pyodide compatibility, so it can run in a browser.

Wrapping Up

These six projects—Simple Calculator, Guess the Number, To-Do List, Weather App, Library Management System, and Snake Game—are just the start. They cover a range of skills from basic Python to working with libraries like requests and pygame. Each project comes with source code you can copy, run, and tweak to make it your own.

Here’s what you can do next:

  • Experiment: Modify the code to add new features.
  • Build a Portfolio: Put these projects on GitHub to show off to recruiters or professors.
  • Explore More: Try libraries like tkinter for GUIs, pandas for data analysis, or flask for web apps.

Python is like a Swiss Army knife—it’s got tools for everything. Keep coding, keep learning, and soon you’ll be building projects that’ll make your friends go, “Arre wah, yeh toh mast hai!” If you need more project ideas or help with debugging, drop a comment or check out communities on X or Stack Overflow.

Happy coding, and don’t forget to take breaks for some chai and samosas!

Next Post Previous Post
No Comment
Add Comment
comment url