Python is a versatile language that’s great for both beginners and experienced developers. Here are 20 mini projects in Python, complete with code examples, that can help you practice and improve your skills.
1. Number Guessing Game
import random def guess_number(): number = random.randint(1, 100) attempts = 0 while True: guess = int(input("Guess the number (between 1 and 100): ")) attempts += 1 if guess < number: print("Too low!") elif guess > number: print("Too high!") else: print(f"Congratulations! You guessed the number in {attempts} attempts.") break guess_number()
2. Simple Calculator
def calculator(): operation = input("Choose an operation (+, -, *, /): ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if operation == '+': print(f"{num1} + {num2} = {num1 + num2}") elif operation == '-': print(f"{num1} - {num2} = {num1 - num2}") elif operation == '*': print(f"{num1} * {num2} = {num1 * num2}") elif operation == '/': print(f"{num1} / {num2} = {num1 / num2}") else: print("Invalid operation!") calculator()
3. BMI Calculator
def bmi_calculator(): weight = float(input("Enter your weight in kg: ")) height = float(input("Enter your height in meters: ")) bmi = weight / (height ** 2) print(f"Your BMI is: {bmi}") bmi_calculator()
4. Palindrome Checker
def is_palindrome(s): s = s.lower().replace(' ', '') return s == s[::-1] word = input("Enter a word or phrase: ") if is_palindrome(word): print(f"'{word}' is a palindrome.") else: print(f"'{word}' is not a palindrome.")
5. To-Do List
def todo_list(): tasks = [] while True: task = input("Enter a task (or 'quit' to stop): ") if task.lower() == 'quit': break tasks.append(task) print("Your To-Do List:") for i, task in enumerate(tasks, 1): print(f"{i}. {task}") todo_list()
6. Hangman Game
import random def hangman(): words = ['python', 'java', 'swift', 'javascript'] word = random.choice(words) guessed = "_" * len(word) word = list(word) guessed = list(guessed) attempts = 6 guessed_letters = [] while attempts > 0: print(' '.join(guessed)) guess = input("Guess a letter: ").lower() if guess in guessed_letters: print("You already guessed that letter.") elif guess in word: for i, letter in enumerate(word): if letter == guess: guessed[i] = guess if "_" not in guessed: print("Congratulations! You won!") break else: attempts -= 1 print(f"Wrong guess. You have {attempts} attempts left.") guessed_letters.append(guess) if attempts == 0: print(f"You lost! The word was {''.join(word)}.") hangman()
7. Currency Converter
def currency_converter(): rate = float(input("Enter the exchange rate from USD to EUR: ")) dollars = float(input("Enter amount in USD: ")) euros = dollars * rate print(f"{dollars} USD is equal to {euros} EUR") currency_converter()
8. Contact Book
contacts = {} def add_contact(name, phone): contacts[name] = phone def view_contacts(): for name, phone in contacts.items(): print(f"{name}: {phone}") while True: choice = input("1. Add Contact 2. View Contacts 3. Quit: ") if choice == '1': name = input("Enter name: ") phone = input("Enter phone number: ") add_contact(name, phone) elif choice == '2': view_contacts() elif choice == '3': break else: print("Invalid choice!")
9. Alarm Clock
import time def alarm_clock(): alarm_time = input("Enter the time to set the alarm (HH:MM): ") print(f"Alarm set for {alarm_time}") while True: current_time = time.strftime("%H:%M") if current_time == alarm_time: print("Wake up!") break time.sleep(1) alarm_clock()
10. Simple Chatbot
def chatbot(): print("Hi! I'm a simple chatbot. Type 'quit' to exit.") while True: user_input = input("You: ") if user_input.lower() == 'quit': print("Goodbye!") break else: print(f"Bot: You said '{user_input}'") chatbot()
11. Password Generator
import random import string def password_generator(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password length = int(input("Enter the length of the password: ")) print(f"Generated Password: {password_generator(length)}")
12. Tic-Tac-Toe
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 5) def check_winner(board, mark): for row in board: if all(s == mark for s in row): return True for col in range(3): if all(row[col] == mark for row in board): return True if all(board[i][i] == mark for i in range(3)) or all(board[i][2 - i] == mark for i in range(3)): return True return False def tic_tac_toe(): board = [[' ' for _ in range(3)]] current_player = "X" for _ in range(9): print_board(board) row, col = map(int, input(f"Player {current_player}, enter row and column: ").split()) if board[row][col] == ' ': board[row][col] = current_player if check_winner(board, current_player): print_board(board) print(f"Player {current_player} wins!") return current_player = "O" if current_player == "X" else "X" else: print("Cell is already taken. Try again.") print_board(board) print("It's a tie!") tic_tac_toe()
13. Weather App (using API)
import requests def get_weather(city): api_key = 'your_api_key' base_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" response = requests.get(base_url) data = response.json() if data['cod'] == 200: main = data['main'] weather = data['weather'][0] print(f"City: {city}") print(f"Temperature: {main['temp']}°C") print(f"Weather: {weather['description']}") else: print("City not found.") city = input("Enter city name: ") get_weather(city)
14. Quiz Game
questions = { "What is the capital of France?": "Paris", "What is 2 + 2?": "4", "What is the color of the sky?": "Blue" } def quiz_game(): score = 0 for question, answer in questions.items(): user_answer = input(question + " ") if user_answer.lower() == answer.lower(): score += 1 print(f"Your score is {score}/{len(questions)}") quiz_game()
15. Rock, Paper, Scissors
import random def rps_game(): choices = ["rock", "paper", "scissors"] computer_choice = random.choice(choices) user_choice = input("Choose rock, paper, or scissors: ").lower() 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!") print(f"Computer chose: {computer_choice}") rps_game()
16. Binary Search Algorithm
def binary_search(arr, x): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == x: return mid elif arr[mid] < x: low = mid + 1 else: high = mid - 1 return -1 arr = [2, 3, 4, 10, 40] x = int(input("Enter the number to search: ")) result = binary_search(arr, x) if result != -1: print(f"Element is present at index {result}") else: print("Element is not present in array")
17. URL Shortener (using API)
import requests def shorten_url(long_url): api_url = "https://api.shrtco.de/v2/shorten" params = {"url": long_url} response = requests.post(api_url, params=params) data = response.json() if data['ok']: return data['result']['short_link'] else: return "Error: Unable to shorten the URL" long_url = input("Enter the URL to shorten: ") short_url = shorten_url(long_url) print(f"Shortened URL: {short_url}")
18. Markdown to HTML Converter
import markdown def markdown_to_html(md_text): html = markdown.markdown(md_text) return html md_text = """ # Heading This is a paragraph with **bold** text and *italic* text. - List item 1 - List item 2 """ html = markdown_to_html(md_text) print(html)
19. Image Resizer
from PIL import Image def resize_image(input_path, output_path, size): with Image.open(input_path) as img: img = img.resize(size, Image.ANTIALIAS) img.save(output_path) input_path = 'input.jpg' output_path = 'output.jpg' size = (800, 600) resize_image(input_path, output_path, size) print("Image resized successfully!")
20. JSON to CSV Converter
import json import csv def json_to_csv(json_file, csv_file): with open(json_file, 'r') as jfile: data = json.load(jfile) with open(csv_file, 'w', newline='') as cfile: writer = csv.writer(cfile) header = data[0].keys() writer.writerow(header) for row in data: writer.writerow(row.values()) json_file = 'data.json' csv_file = 'data.csv' json_to_csv(json_file, csv_file) print("JSON data converted to CSV successfully!")
These mini projects cover a wide range of applications, from games and utilities to data processing and web interactions. They offer practical experience with Python and can be used as a foundation for more complex projects.