20 Python Programming Projects for Undergraduates
Engaging project ideas complete with explanations and sample solutions
Highlights
- Wide-ranging Projects: Cover beginning to advanced levels from games and utilities to data analysis.
- Practical Solutions: Each project includes sample code and implementation ideas.
- Scalable Complexity: Projects easily adapted to different levels of skills and learning objectives.
Project Ideas and Solutions
1. Number Guessing Game
Description
This project generates a random number within a specified range. The player attempts to guess the number with feedback provided on whether their guess is too high or too low.
Sample Code
import random
def number_guessing_game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
print(f"Congratulations! You guessed the number in {attempts} attempts.")
number_guessing_game()
2. Basic Calculator
Description
Build a simple calculator that performs basic arithmetic operations such as addition, subtraction, multiplication, and division.
Sample Code
def calculator():
while True:
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '5':
break
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("Error: Division by zero.")
else:
print("Invalid choice.")
calculator()
3. Rock, Paper, Scissors Game
Description
Create a game where the player competes against the computer. The computer randomly selects rock, paper, or scissors and the winner is determined based on standard rules.
Sample Code
import random
def rock_paper_scissors():
choices = ['rock', 'paper', 'scissors']
while True:
user_choice = input("Enter rock, paper, or scissors (or quit to exit): ").lower()
if user_choice == 'quit':
break
if user_choice not in choices:
print("Invalid choice, try again.")
continue
computer_choice = random.choice(choices)
print(f"Computer chose: {computer_choice}")
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'paper' and computer_choice == 'rock') or \
(user_choice == 'scissors' and computer_choice == 'paper'):
print("You win!")
else:
print("You lose!")
rock_paper_scissors()
4. Simple To-Do List Application
Description
Develop a program to manage tasks. Users can add new tasks, delete specific tasks, and view a list of pending tasks.
Sample Code
def todo_list():
tasks = []
while True:
print("\n1. Add Task")
print("2. Delete Task")
print("3. View Tasks")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
task = input("Enter a new task: ")
tasks.append(task)
elif choice == '2':
try:
task_num = int(input("Enter task number to delete: "))
del tasks[task_num - 1]
except (IndexError, ValueError):
print("Invalid task number.")
elif choice == '3':
print("To-Do List:")
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
elif choice == '4':
break
else:
print("Invalid option.")
todo_list()
5. Dice Rolling Simulator
Description
Simulate dice rolls by generating random numbers between 1 and 6. The user can roll the dice repeatedly until they choose to exit.
Sample Code
import random
def dice_rolling_simulator():
while True:
choice = input("Roll the dice? (yes/no): ").lower()
if choice == 'yes':
print(f"You rolled a: {random.randint(1, 6)}")
elif choice == 'no':
break
else:
print("Please answer with yes or no.")
dice_rolling_simulator()
6. Email Slicer
Description
This project takes an email address and extracts the username and the domain, introducing string manipulation techniques.
Sample Code
def email_slicer():
email = input("Enter your email address: ")
try:
username, domain = email.split("@")
print(f"Username: {username}")
print(f"Domain: {domain}")
except ValueError:
print("Invalid email address.")
email_slicer()
7. Number to Words Converter
Description
Convert a given numerical value into its equivalent English word representation, practicing conversion logic and recursion or loop-based solutions.
Sample Code
import num2words # Ensure you have installed this library using pip
def number_to_words():
try:
number = int(input("Enter a number to convert: "))
words = num2words.num2words(number)
print(f"{number} in words is: {words}")
except Exception as e:
print("Error converting number to words:", e)
number_to_words()
8. Contact List Manager
Description
Create a console-based application that allows users to store and manage contacts including names, phone numbers, and email addresses.
Sample Code
def contact_list_manager():
contacts = {}
while True:
print("\n1. Add Contact")
print("2. View Contacts")
print("3. Exit")
choice = input("Enter choice: ")
if choice == '1':
name = input("Contact name: ")
phone = input("Phone number: ")
email = input("Email: ")
contacts[name] = {'phone': phone, 'email': email}
elif choice == '2':
for name, info in contacts.items():
print(f"Name: {name} | Phone: {info['phone']} | Email: {info['email']}")
elif choice == '3':
break
else:
print("Invalid option.")
contact_list_manager()
9. Password Generator
Description
Generate a secure, randomized password based on user-defined length and such options as inclusion of uppercase letters, numbers, or special characters.
Sample Code
import random
import string
def password_generator():
length = int(input("Enter password length: "))
use_upper = input("Include uppercase letters? (yes/no): ").lower() == 'yes'
use_numbers = input("Include numbers? (yes/no): ").lower() == 'yes'
use_special = input("Include special characters? (yes/no): ").lower() == 'yes'
characters = string.ascii_lowercase
if use_upper:
characters += string.ascii_uppercase
if use_numbers:
characters += string.digits
if use_special:
characters += string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
print("Generated password:", password)
password_generator()
10. Web Scraper
Description
Create a script that fetches content from websites and extracts useful information. Use libraries like requests and BeautifulSoup for web scraping.
Sample Code
import requests
from bs4 import BeautifulSoup
def web_scraper():
url = input("Enter a URL: ")
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.prettify())
web_scraper()
11. Tic Tac Toe Game
Description
Develop a two-player Tic Tac Toe game that tracks moves on a simple board and checks win conditions.
Sample Code
def tic_tac_toe():
board = [' ' for _ in range(9)]
current_player = 'X'
def print_board():
print(f"{board[0]} | {board[1]} | {board[2]}")
print("--+---+--")
print(f"{board[3]} | {board[4]} | {board[5]}")
print("--+---+--")
print(f"{board[6]} | {board[7]} | {board[8]}")
for _ in range(9):
print_board()
move = int(input(f"Player {current_player}, choose your position (1-9): ")) - 1
if board[move] == ' ':
board[move] = current_player
# Check win conditions here if desired.
current_player = 'O' if current_player == 'X' else 'X'
else:
print("Invalid move, try again.")
print_board()
tic_tac_toe()
12. Digital Clock
Description
Build a digital clock using Tkinter that shows the current time and can also be extended to include an alarm feature.
Sample Code
import tkinter as tk
import time
def digital_clock():
root = tk.Tk()
root.title("Digital Clock")
clock_label = tk.Label(root, font=("Arial", 48), bg="black", fg="white")
clock_label.pack(expand=True, fill="both")
def update_time():
current_time = time.strftime("%H:%M:%S")
clock_label.config(text=current_time)
clock_label.after(1000, update_time)
update_time()
root.mainloop()
digital_clock()
13. Chatbot
Description
Create a simple text-based chatbot using Python. The bot responds based on a set of predefined keywords.
Sample Code
def chatbot():
responses = {
"hello": "Hi! How can I help you?",
"bye": "Goodbye!",
"thanks": "You're welcome!"
}
while True:
user_input = input("You: ").lower()
if user_input == "quit":
break
print("Bot:", responses.get(user_input, "Sorry, I do not understand that."))
chatbot()
14. Currency Converter
Description
Design a converter to change currencies based on predefined exchange rates. It illustrates the use of arithmetic operations and user input.
Sample Code
def currency_converter():
exchange_rates = {"USD": 1, "EUR": 0.88, "GBP": 0.76}
while True:
currency = input("Enter currency (USD, EUR, GBP) or exit: ").upper()
if currency == "EXIT":
break
amount = float(input(f"Enter amount in {currency}: "))
for curr, rate in exchange_rates.items():
if curr != currency:
converted = amount * exchange_rates[currency] / rate
print(f"{amount} {currency} = {converted:.2f} {curr}")
currency_converter()
15. Hangman Game
Description
Implement the classic Hangman game where a random word is selected and the player guesses letters until the word is revealed or tries run out.
Sample Code
import random
def hangman():
words = ['apple', 'banana', 'cherry']
word = random.choice(words)
display = ['_' for _ in word]
attempts = 6
guessed_letters = set()
while attempts > 0 and '_' in display:
print("Current word:", " ".join(display))
guess = input("Guess a letter or the full word: ").lower()
if len(guess) == 1:
if guess in guessed_letters:
print("Already guessed!")
elif guess in word:
for index, letter in enumerate(word):
if letter == guess:
display[index] = guess
else:
attempts -= 1
print(f"Wrong guess! Attempts left: {attempts}")
guessed_letters.add(guess)
elif guess == word:
display = list(word)
break
else:
attempts -= 1
print(f"Wrong guess! Attempts left: {attempts}")
if '_' not in display:
print("Congratulations, you guessed the word:", word)
else:
print("Out of attempts! The word was:", word)
hangman()
16. Simple Stopwatch
Description
Develop a stopwatch with functionalities to start, stop, and reset. This project uses time management operations with loops.
Sample Code
import time
def stopwatch():
start_time = None
elapsed = 0
while True:
print("\n1. Start\n2. Stop\n3. Reset\n4. Exit")
choice = input("Choose an option: ")
if choice == '1' and start_time is None:
start_time = time.time()
print("Stopwatch started!")
elif choice == '2' and start_time is not None:
elapsed += time.time() - start_time
start_time = None
print(f"Elapsed time: {elapsed:.2f} seconds")
elif choice == '3':
start_time = None
elapsed = 0
print("Stopwatch reset.")
elif choice == '4':
break
else:
print("Invalid option or stopwatch already running/stopped.")
stopwatch()
17. Text Adventure Game
Description
Create an interactive text-based adventure game with multiple story paths. Users make choices that influence the outcome.
Sample Code
def text_adventure():
print("Welcome to the Adventure Game!")
current_room = "start"
while True:
if current_room == "start":
choice = input("You are in a dark room. Choose direction (north/east): ").lower()
if choice == "north":
current_room = "hallway"
elif choice == "east":
current_room = "garden"
else:
print("Invalid direction.")
elif current_room == "hallway":
print("You are in a long hallway.")
if input("Go back? (yes/no): ").lower() == "yes":
current_room = "start"
else:
print("You continue and reach a dead end.")
break
elif current_room == "garden":
print("You are in a beautiful garden with a pond.")
if input("Go back? (yes/no): ").lower() == "yes":
current_room = "start"
else:
break
print("Game over.")
text_adventure()
18. Machine Learning Recommendation System (Basic)
Description
This advanced project lets students explore building a recommendation engine for movies or products using machine learning libraries like scikit-learn.
Implementation Guidelines
Start with a dataset, perform data preprocessing, and utilize collaborative filtering or content-based filtering techniques to recommend items.
# Pseudocode Outline
# 1. Import libraries such as pandas, scikit-learn
# 2. Load and clean dataset (e.g., movie ratings)
# 3. Use a model like KNN or a clustering algorithm for recommendations
# 4. Output recommended items based on similarity measure
19. Automated File Organizer
Description
Develop a script that automatically organizes files in a directory based on their file types (like images, documents, etc.).
Sample Code
import os
import shutil
def organize_files(directory):
file_types = {"Images": (".jpg", ".png", ".gif"),
"Documents": (".pdf", ".docx", ".txt"),
"Videos": (".mp4", ".mov")}
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
for folder, extensions in file_types.items():
if filename.lower().endswith(extensions):
target_folder = os.path.join(directory, folder)
if not os.path.exists(target_folder):
os.makedirs(target_folder)
shutil.move(file_path, target_folder)
break
# Example usage:
# organize_files("/path/to/your/directory")
20. AI-Powered Chatbot
Description
Implement a more advanced chatbot using natural language processing techniques. Integrate libraries like NLTK or even deep learning models if desired.
Implementation Guidelines
Focus on training a simple conversational model or using pre-trained language models to handle basic queries interactively.
# Pseudocode Outline:
# 1. Use the NLTK library for basic NLP
# 2. Define intents and response mappings
# 3. Create a loop accepting user input and matching it to the most similar intent
# 4. Respond accordingly
Project Overview Table
| Project | Description | Key Skills |
|---|---|---|
| Number Guessing Game | Random number generation and user feedback | Loops, Conditionals, Random Module |
| Basic Calculator | Perform arithmetic operations | Functions, User Input, Arithmetic |
| Rock, Paper, Scissors | Classic game with random choices | Random Module, Conditional Logic |
| To-Do List App | Manage and display tasks | Data Structures, Loops, User Input |
| Dice Rolling Simulator | Simulate dice rolls using random numbers | Random Module, Loops |
| Email Slicer | Extract username and domain from email | String Manipulation |
| Number to Words | Convert numbers into their word equivalents | Conversion Logic, Libraries |
| Contact List | Manage a simple contact directory | Dictionaries, User Input |
| Password Generator | Create secure passwords | Random, String Handling |
| Web Scraper | Extract data from websites | Requests, BeautifulSoup |
| Tic Tac Toe | Game logic for two players | Lists, Loops, Conditionals |
| Digital Clock | Display a live clock using GUI | TKinter, Time |
| Chatbot | Interactive response system | Conditional Logic, Dictionaries |
| Currency Converter | Convert between various currencies | Arithmetic, User Input |
| Hangman Game | Word guess game with limited attempts | Loops, String Manipulation |
| Simple Stopwatch | Track elapsed time with start/stop functions | Time Module, Loops |
| Text Adventure Game | Interactive narrative game | Control Flow, Input |
| ML Recommendation System | Analyze and recommend items based on data | Scikit-learn, Data Preprocessing |
| File Organizer | Auto-sorting files by type | OS, Shutil |
| AI-Powered Chatbot | Advanced NLP based interactive system | NLP, Machine Learning |
References
- Python Projects for Beginners - Veritas AI
- 30 Fun Python Projects - Inspirit AI
- Python Projects - Real Python
- Python Projects Beginner to Advanced - GeeksforGeeks
- Python Projects for Beginners - Dataquest
Related Queries
Last updated March 9, 2025