Python Projects

Learn by doing!

BUILD A  CALCULATOR 

Here's a simple command-line calculator application in Python.

This code defines functions for basic arithmetic operations (addition, subtraction, multiplication, and division) and then prompts the user to select an operation and input numbers accordingly. The program then performs the chosen operation and displays the result.

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!"
     else:
         return x / y  

print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")  

while True:
     choice = input("Enter choice (1/2/3/4): ")
     if choice in ('1', '2', '3', '4'):
         num1 = float(input("Enter first number: "))
         num2 = float(input("Enter second number: "))

         if choice == '1':
             print("Result:", add(num1, num2))
         elif choice == '2':
             print("Result:", subtract(num1, num2))
         elif choice == '3':
             print("Result:", multiply(num1, num2))
         elif choice == '4':
             print("Result:", divide(num1, num2))
         break
     else:
         print("Invalid Input") 

BUILD A  Temperature converteR 

Here's a simple command-line temperature converter application in Python.

This code defines functions to convert temperature from Celsius to Fahrenheit and vice versa. The program prompts the user to select a conversion type, inputs the temperature value, and then performs the conversion accordingly, displaying the result.

def celsius_to_fahrenheit(celsius):
     return (celsius * 9/5) + 32  

def fahrenheit_to_celsius(fahrenheit):
     return (fahrenheit - 32) * 5/9  

print("Select conversion:")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")  

while True:
     choice = input("Enter choice (1/2): ")

     if choice in ('1', '2'):
         if choice == '1':
             celsius = float(input("Enter temperature in Celsius: "))
             print("Temperature in Fahrenheit:", celsius_to_fahrenheit(celsius))
         elif choice == '2':
             fahrenheit = float(input("Enter temperature in Fahrenheit: "))
             print("Temperature in Celsius:", fahrenheit_to_celsius(fahrenheit))
         break
     else:
         print("Invalid Input") 

BUILD A  To-Do List 

Here's a simple command-line To-Do list application in Python.

This code allows users to manage a simple To-Do list. Users can view tasks, add new tasks, remove tasks, and quit the application. Tasks are stored in a list and displayed with their corresponding indices. Users can choose options by entering the respective numbers.

# Function to display the To-Do list
def display_tasks(tasks):
     if not tasks:
         print("No tasks in the list.")
     else:
         print("Tasks:")
         for i, task in enumerate(tasks, 1):
             print(f"{i}. {task}")  

# Function to add a task to the list
def add_task(tasks, new_task):
     tasks.append(new_task)
     print("Task added successfully.")

# Function to remove a task from the list
def remove_task(tasks, task_index):
     if 0 < task_index <= len(tasks):
         removed_task = tasks.pop(task_index - 1)
         print(f"Task '{removed_task}' removed successfully.")
     else:
         print("Invalid task index.")  

# Main function
def main():
     tasks = [ ]
      while True:
         print("nSelect an option:")
         print("1. Display To-Do list")
         print("2. Add task")
         print("3. Remove task")
         print("4. Quit")

         choice = input("Enter choice (1/2/3/4): ")

          if choice == '1':
             display_tasks(tasks)
         elif choice == '2':
             new_task = input("Enter the new task: ")
             add_task(tasks, new_task)
         elif choice == '3':
             display_tasks(tasks)
             task_index = int(input("Enter the index of the task to remove: "))
             remove_task(tasks, task_index)
         elif choice == '4':
             print("Exiting...")
             break
         else:
             print("Invalid input. Please enter a number from 1 to 4.")

if __name__ == "__main__":
     main() 

BUILD AN  Address Book 

Here's a basic command-line address book application in Python.

This code allows users to manage a simple address book. Users can view contacts, add new contacts, remove contacts, and quit the application. Contacts are stored as dictionaries containing the name and phone number. Users can choose options by entering the respective numbers.

# Function to display the address book
def display_contacts(contacts):
     if not contacts:
         print("Address book is empty.")
     else:
         print("Contacts:")
         for i, contact in enumerate(contacts, 1):
             print(f"{i}. {contact['name']}: {contact['phone']}")  

# Function to add a contact to the address book
def add_contact(contacts, name, phone):
     contacts.append({'name': name, 'phone': phone})
     print("Contact added successfully.")  

# Function to remove a contact from the address book
def remove_contact(contacts, index):
     if 0 < index <= len(contacts):
         removed_contact = contacts.pop(index - 1)
         print(f"Contact '{removed_contact['name']}' removed successfully.")
     else:
         print("Invalid contact index.")  

# Main function
def main():
     contacts = [ ]

     while True:
         print("nSelect an option:")
         print("1. Display Address Book")
         print("2. Add Contact")
         print("3. Remove Contact")
         print("4. Quit")

         choice = input("Enter choice (1/2/3/4): ")

         if choice == '1':
             display_contacts(contacts)
         elif choice == '2':
             name = input("Enter the name of the contact: ")
             phone = input("Enter the phone number of the contact: ")
             add_contact(contacts, name, phone)
         elif choice == '3':
             display_contacts(contacts)
             index = int(input("Enter the index of the contact to remove: "))
             remove_contact(contacts, index)
         elif choice == '4':
             print("Exiting...")
             break
         else:
             print("Invalid input. Please enter a number from 1 to 4.")  

if __name__ == "__main__":
     main() 

BUILD AN  Expense Tracker 

Here's a simple command-line Expense Tracker application in Python.

This code allows users to manage a simple expense tracker. Users can view expenses, add new expenses, remove expenses, and quit the application. Expenses are stored as dictionaries containing the date, description, and amount. Users can choose options by entering the respective numbers.

# Function to display the expense tracker
def display_expenses(expenses):
     if not expenses:
         print("Expense tracker is empty.")
     else:
         print("Expenses:")
         for i, expense in enumerate(expenses, 1):
             print(f"{i}. {expense['date']}: {expense['description']} - ${expense['amount']}")  

# Function to add an expense to the tracker
def add_expense(expenses, date, description, amount):
     expenses.append({'date': date, 'description': description, 'amount': amount})
     print("Expense added successfully.")  

# Function to remove an expense from the tracker
def remove_expense(expenses, index):
     if 0 < index <= len(expenses):
         removed_expense = expenses.pop(index - 1)
         print(f"Expense '{removed_expense['description']}' removed successfully.")
     else:
         print("Invalid expense index.")  

# Main function
def main():
     expenses = [ ]
      while True:
         print("nSelect an option:")
         print("1. Display Expense Tracker")
         print("2. Add Expense")
         print("3. Remove Expense")
         print("4. Quit")

         choice = input("Enter choice (1/2/3/4): ")
          if choice == '1':
             display_expenses(expenses)
         elif choice == '2':
             date = input("Enter the date of the expense (e.g., MM-DD-YYYY): ")
             description = input("Enter a description of the expense: ")
             amount = float(input("Enter the amount of the expense: $"))
             add_expense(expenses, date, description, amount)
         elif choice == '3':
             display_expenses(expenses)
             index = int(input("Enter the index of the expense to remove: "))
             remove_expense(expenses, index)
         elif choice == '4':
             print("Exiting...")
             break
         else:
             print("Invalid input. Please enter a number from 1 to 4.")  

if __name__ == "__main__":
     main() 

BUILD A  Text-Based RPG 

Here's a simplified text-based RPG (Role-Playing Game) in Python. In this game, the player navigates through different rooms, encounters enemies, and makes choices.

This code creates a simple text-based RPG where the player moves through rooms in a dungeon. They encounter enemies in some rooms and must defeat them to progress. The game ends when the player reaches the treasure room, or if their health drops to zero.

import random
 class Player:
     def __init__(self, name, hp=100, attack=10):
         self.name = name
         self.hp = hp
         self.attack = attack

     def is_alive(self):
         return self.hp > 0

     def take_damage(self, damage):
         self.hp -= damage

     def attack_enemy(self, enemy):
         damage = random.randint(1, self.attack)
         enemy.take_damage(damage)
         print(f"{self.name} attacks {enemy.name} for {damage} damage.")  

class Enemy:
     def __init__(self, name, hp, attack):
         self.name = name
         self.hp = hp
         self.attack = attack

     def is_alive(self):
         return self.hp > 0

     def take_damage(self, damage):
         self.hp -= damage

     def attack_player(self, player):
         damage = random.randint(1, self.attack)
         player.take_damage(damage)
         print(f"{self.name} attacks {player.name} for {damage} damage.")  

class Room:
     def __init__(self, name, description, enemy=None):
         self.name = name
         self.description = description
         self.enemy = enemy

     def display_room(self):
         print(f"You are in {self.name}: {self.description}")
         if self.enemy:
             print(f"You encounter a {self.enemy.name}!")  

def main():
     player_name = input("Enter your name: ")
     player = Player(player_name)

     room1 = Room("Room 1", "a dark and gloomy room")
     room2 = Room("Room 2", "a dimly lit corridor")
     room3 = Room("Room 3", "a spooky chamber", Enemy("Skeleton", hp=20, attack=8))
     room4 = Room("Room 4", "a treasure room")

     rooms = [room1, room2, room3, room4]
     current_room_index = 0

     print("Welcome to the Dungeon!")
     while player.is_alive():
         current_room = rooms[current_room_index]
         current_room.display_room()

         if current_room.enemy:
             while current_room.enemy.is_alive() and player.is_alive():
                 player.attack_enemy(current_room.enemy)
                 if current_room.enemy.is_alive():
                     current_room.enemy.attack_player(player)

             if not current_room.enemy.is_alive():
                 print(f"{current_room.enemy.name} defeated!")

         if current_room_index == len(rooms) - 1:
             print("Congratulations! You have reached the treasure room!")
             break

         if player.is_alive():
             move = input("Do you want to move to the next room? (yes/no): ")
             if move.lower() == 'yes':
                 current_room_index += 1
             else:
                 print("Game over! You decide to stay in the dungeon.")
                 break

      if not player.is_alive():
         print("Game over! You have been defeated.")
if __name__ == "__main__":
     main() 

BUILD A  Password Generator 

Here's a simple password generator application in Python.

This code generates a random password with the specified length. It includes uppercase letters, lowercase letters, digits, and special characters. The user can specify the length of the password when running the program, and a default length of 12 is used if no length is provided.

import random
import string  

def generate_password(length=12):
     characters = string.ascii_letters + string.digits + string.punctuation
     password = ''.join(random.choice(characters) for _ in range(length))
     return password  

def main():
     print("Welcome to the Password Generator!")
     while True:
         length = int(input("Enter the length of the password (default is 12): "))
         if length <= 0:
             print("Invalid length. Please enter a positive number.")
         else:
             break

     password = generate_password(length)
     print("Generated Password:", password)  

if __name__ == "__main__":
     main() 

BUILD A  Reverse User Input 

Here's a simple Python application that takes user input and prints it in reverse.

This code prompts the user to input a string and then prints the reverse of that string. It uses Python's string slicing technique ([::-1]) to reverse the input string.

def reverse_input():
     user_input = input("Enter a string: ")
     reversed_input = user_input[::-1]
     return reversed_input  

def main():
     reversed_string = reverse_input()
     print("Reversed input:", reversed_string)  

if __name__ == "__main__":
     main()