LEARN COMPLETE PYTHON IN 24 HOURS

14. Mini Projects & Practice Ideas

Build these projects step-by-step. They are designed to be simple at first but expandable.

14.1 Calculator Program

A simple console-based calculator that performs basic operations.

Features:

  • Add, subtract, multiply, divide

  • Handle division by zero

  • Loop until user exits

Full Code:

Python

def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x y def divide(x, y): if y == 0: return "Error! Division by zero." return x / y operations = { '+': add, '-': subtract, '': multiply, '/': divide } print("=== Simple Calculator (2026 Edition) ===") print("Operations: + - /") print("Type 'exit' to quit\n") while True: num1_input = input("Enter first number: ").strip() if num1_input.lower() == 'exit': print("Goodbye!") break try: num1 = float(num1_input) except ValueError: print("Invalid number! Try again.") continue op = input("Enter operator (+ - /): ").strip() if op not in operations: print("Invalid operator!") continue try: num2 = float(input("Enter second number: ")) except ValueError: print("Invalid number!") continue result = operations[op](num1, num2) print(f"{num1} {op} {num2} = {result}\n")

Sample Output:

text

=== Simple Calculator (2026 Edition) === Operations: + - / Type 'exit' to quit Enter first number: 25 Enter operator (+ - /): Enter second number: 4 25.0 4.0 = 100.0 ... Enter first number: exit Goodbye!

Improvements to try:

  • Add more operations (power **, modulo %, square root)

  • Keep history of calculations

  • Use eval() cautiously for advanced mode

14.2 Guess the Number Game

Computer picks a random number — user guesses it.

Features:

  • Hints (too high / too low)

  • Count attempts

  • Uses random module

Full Code:

Python

import random print("=== Guess the Number Game ===") print("I'm thinking of a number between 1 and 100.") print("Can you guess it?\n") secret_number = random.randint(1, 100) attempts = 0 while True: try: guess = int(input("Your guess: ")) attempts += 1 if guess == secret_number: print(f"Congratulations! You guessed it in {attempts} attempts! 🎉") break elif guess < secret_number: print("Too low! Try higher.") else: print("Too high! Try lower.") except ValueError: print("Please enter a valid number!")

Sample Output:

text

=== Guess the Number Game === I'm thinking of a number between 1 and 100. Can you guess it? Your guess: 50 Too high! Try lower. Your guess: 25 Too low! Try higher. ... Your guess: 42 Congratulations! You guessed it in 7 attempts! 🎉

Improvements:

  • Add difficulty levels (1-10, 1-100, 1-1000)

  • Limit maximum attempts

  • Play again option

14.3 To-Do List (using lists/dictionaries)

A command-line to-do list manager.

Features:

  • Add, view, remove tasks

  • Uses list of dictionaries for better structure

Full Code:

Python

todo_list = [] print("=== To-Do List Manager ===") while True: print("\n1. Add Task") print("2. View Tasks") print("3. Remove Task") print("4. Exit") choice = input("Choose (1-4): ").strip() if choice == '1': task = input("Enter task: ").strip() priority = input("Priority (High/Medium/Low): ").strip().capitalize() todo_list.append({"task": task, "priority": priority, "done": False}) print("Task added!") elif choice == '2': if not todo_list: print("No tasks yet!") else: print("\nYour To-Do List:") for i, item in enumerate(todo_list, 1): status = "" if item["done"] else " " print(f"{i}. [{status}] {item['task']} ({item['priority']})") elif choice == '3': if not todo_list: print("No tasks to remove!") else: try: num = int(input("Task number to remove: ")) if 1 <= num <= len(todo_list): removed = todo_list.pop(num - 1) print(f"Removed: {removed['task']}") else: print("Invalid number!") except ValueError: print("Enter a valid number!") elif choice == '4': print("Goodbye! Stay productive!") break else: print("Invalid choice!")

Improvements:

  • Mark task as done

  • Save/load from file

  • Sort by priority

14.4 Password Generator

Generate strong random passwords.

Features:

  • Custom length

  • Include letters, numbers, symbols

Full Code:

Python

import random import string print("=== Password Generator ===") length = int(input("Password length (8-32 recommended): ")) use_upper = input("Include uppercase? (y/n): ").lower() == 'y' use_numbers = input("Include numbers? (y/n): ").lower() == 'y' use_symbols = input("Include symbols? (y/n): ").lower() == 'y' characters = string.ascii_lowercase if use_upper: characters += string.ascii_uppercase if use_numbers: characters += string.digits if use_symbols: characters += string.punctuation if not characters: print("No character types selected! Using lowercase only.") characters = string.ascii_lowercase password = ''.join(random.choice(characters) for _ in range(length)) print("\nGenerated Password:", password)

Sample Output:

text

=== Password Generator === Password length (8-32 recommended): 12 Include uppercase? (y/n): y Include numbers? (y/n): y Include symbols? (y/n): y Generated Password: kP9#mL2$xQv8

Improvements:

  • Generate multiple passwords

  • Copy to clipboard (use pyperclip module)

  • Check password strength

14.5 Rock Paper Scissors Game

Classic game against computer.

Full Code:

Python

import random print("=== Rock Paper Scissors ===") print("Choices: rock, paper, scissors") print("Type 'exit' to quit\n") choices = ["rock", "paper", "scissors"] while True: user_choice = input("Your choice: ").lower().strip() if user_choice == 'exit': print("Thanks for playing!") 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("Computer wins!")

Sample Output:

text

Your choice: rock Computer chose: scissors You win! 🎉

Improvements:

  • Keep score (wins, losses, ties)

  • Add "lizard spock" variant

  • Best of 3/5 rounds

Final Tip for All Projects:

  • Run them in VS Code or any editor

  • Add error handling (try-except) everywhere

  • Make them prettier with colors (use colorama module later)

  • Share your versions on GitHub for portfolio!

These projects will help solidify your Python basics.

15. Best Practices & Next Steps

You’ve learned the fundamentals — now focus on writing clean, professional Python code and planning your next journey.

15.1 Naming Conventions (PEP 8)

PEP 8 is Python’s official style guide — follow it to make your code readable and consistent with most Python developers.

Key Naming Rules:

TypeConventionExampleCorrect?Variable / Functionsnake_caseuser_name, calculate_totalYesConstantUPPER_CASE_WITH_UNDERSCORESMAX_USERS, PI_VALUEYesClassCamelCaseUserProfile, BankAccountYesModule / File namesnake_case.pyuser_utils.py, data_processor.pyYesSingle leading underscoreInternal use (private)_internal_helperCommonDouble leading underscoreName mangling (advanced)__private_methodAdvanced

Quick PEP 8 Tips:

  • Lines ≤ 79 characters (or 120 max in modern projects)

  • 4 spaces indentation (never tabs)

  • Spaces around operators: x = y + 2 (not x=y+2)

  • No spaces inside parentheses: func(arg1, arg2) (not func( arg1, arg2 ))

  • One blank line between functions/classes, two between top-level functions

Example – Good vs Bad

Python

# Bad UserAge=25 def CalculateArea(r):return 3.14*r*r # Good (PEP 8) user_age = 25 def calculate_area(radius): return 3.14159 radius radius

Tool to help: Install black formatter or use VS Code’s built-in formatter with Python extension.

15.2 Writing Readable Code

“Code is read much more often than it is written.” — Follow these rules:

  1. Use meaningful namestotal_price > tp, calculate_area > f

  2. Keep functions small One function = one responsibility (ideally < 20–30 lines)

  3. Write comments only when needed Explain why, not what

Python

# Good comment # Adjust for Indian GST 18% price_with_tax = price * 1.18 # Bad (obvious) # add 1 to count count += 1

  1. Use blank lines wisely Separate logical blocks

  2. Follow DRY (Don’t Repeat Yourself) If you copy-paste code → make a function!

  3. Handle errors gracefully Use try-except instead of letting program crash

Readable Example:

Python

def get_final_price(base_price, discount_percent=0, tax_rate=0.18): """ Calculate final price after discount and tax. Default tax is 18% (GST in India). """ discounted = base_price (1 - discount_percent / 100) final = discounted (1 + tax_rate) return round(final, 2)

15.3 Common Beginner Mistakes to Avoid

MistakeWhy it's badHow to fixUsing global too muchMakes code hard to understand/debugPass variables as parametersMutable default argumentsUnexpected behaviorUse None and initialize insidefrom module import *Name conflicts, hard to traceImport specific or use aliasNot handling exceptionsProgram crashes on bad inputUse try-except blocksComparing with is instead of ==Wrong for values (except None/True)Use == for value, is for identityModifying list while loopingSkips items or errorsLoop over copy or use list comprehensionForgetting to convert input()"25" + 1 → errorUse int(input()), float(input())Long lines / no formattingHard to readFollow PEP 8, use black formatter

Mutable Default Argument Trap Example (Common Bug):

Python

def add_item(item, my_list=[]): # Dangerous! my_list.append(item) return my_list print(add_item(1)) # [1] print(add_item(2)) # [1, 2] ← unexpected!

Correct Way:

Python

def add_item(item, my_list=None): if my_list is None: my_list = [] my_list.append(item) return my_list

15.4 What to Learn After Basics (file handling, OOP, libraries…)

You now know the core of Python — here’s the natural next path:

  1. File Handling Read/write text files, CSV, JSON open(), with statement, json module

  2. Object-Oriented Programming (OOP) Classes, objects, inheritance, encapsulation init, self, @property, super()

  3. Popular Libraries & Ecosystems

    • Data: pandas, numpy, matplotlib

    • Web: requests, flask/fastapi, beautifulsoup

    • Automation: selenium, pyautogui

    • AI/ML: scikit-learn, tensorflow/pytorch (basics)

  4. Error Handling & Debuggingtry-except-else-finally, logging, pdb debugger

  5. Virtual Environments & pipvenv, requirements.txt, pip install

  6. Git & GitHub Version control — essential for real projects

  7. Projects Build: CLI app, web scraper, simple website (Flask), data dashboard, automation script

Suggested Learning Path (2026):

  • Weeks 1–2 → File I/O + Exception Handling

  • Weeks 3–5 → OOP (classes & inheritance)

  • Weeks 6+ → Pick one domain: Data Analysis (pandas) or Web (Flask/FastAPI)