Create a program that calculates the simple interest given the principal amount, rate of interest, and time period.
# Simple Interest Calculator
# User inputs
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (in %): "))
time = float(input("Enter the time period (in years): "))
# Calculate simple interest
interest = (principal * rate * time) / 100
# Display result
print(f"The simple interest is: {interest}")
Create a program that calculates the Body Mass Index (BMI) given the weight and height of a person.
# BMI Calculator
# User inputs
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))
# Calculate BMI
bmi = weight / (height ** 2)
# Display result
print(f"Your BMI is: {bmi}")
Create a program that calculates the tip amount and total bill based on the bill amount and desired tip percentage.
# Tip Calculator
# User inputs
bill_amount = float(input("Enter the bill amount: "))
tip_percentage = float(input("Enter the tip percentage: "))
# Calculate tip and total amount
tip_amount = (bill_amount * tip_percentage) / 100
total_amount = bill_amount + tip_amount
# Display results
print(f"Tip amount: {tip_amount}")
print(f"Total bill amount: {total_amount}")
Create a Currency Converter in Python
# Currency Converter
# User inputs
amount = float(input("Enter the amount in your currency: "))
conversion_rate = float(input("Enter the conversion rate to the target currency: "))
# Convert amount
converted_amount = amount * conversion_rate
# Display result
print(f"The converted amount is: {converted_amount}")
Create a program that converts temperature from Celsius to Fahrenheit and vice versa
# Temperature Converter
# User input
choice = input("Type 'C' to convert Celsius to Fahrenheit or 'F' to convert Fahrenheit to Celsius: ").upper()
if choice == 'C':
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")
elif choice == 'F':
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}°F is equal to {celsius}°C")
else:
print("Invalid choice!")
Create a Rock, Paper, Scissors game where the user can play against the computer. Use if, elif, and else statements.
import random
def game():
choices = ["rock", "paper", "scissors"]
computer = random.choice(choices)
user = input("Enter your choice (rock, paper, scissors): ").lower()
while user not in choices:
user = input("Invalid input. Enter your choice (rock, paper, scissors): ").lower()
if user == computer:
print(f"Computer chose {computer}. It's a tie!")
elif (user == "rock" and computer == "scissors") or (user == "scissors" and computer == "paper") or (user == "paper" and computer == "rock"):
print(f"Computer chose {computer}. You win!")
else:
print(f"Computer chose {computer}. You lose!")
game()
Create a To-Do List App that allows users to add, remove, and mark tasks as completed. Use if, elif, and else statements to handle user input and update the to-do list.
todo_list = []
def add_task():
task = input("Enter a task: ")
todo_list.append({"task": task, "completed": False})
def remove_task():
task_index = int(input("Enter the task number to remove: ")) - 1
if task_index >= 0 and task_index < len(todo_list):
del todo_list[task_index]
else:
print("Invalid task number.")
def mark_completed():
task_index = int(input("Enter the task number to mark as completed: ")) - 1
if task_index >= 0 and task_index < len(todo_list):
todo_list[task_index]["completed"] = True
else:
print("Invalid task number.")
while True:
print("\nTo-Do List App Menu:")
print("1. Add Task")
print("2. Remove Task")
print("3. Mark Task as Completed")
print("4. Display To-Do List")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
add_task()
elif choice == 2:
remove_task()
elif choice == 3:
mark_completed()
elif choice == 4:
for i, task in enumerate(todo_list, 1):
print(f"{i}. {task['task']} {'(Completed)' if task['completed'] else ''}")
elif choice == 5:
print("Goodbye!")
hreak
else:
print("Invalid choice. Please try again!")
Create a Simple Chatbot that responds to user input using if, elif, and else statements.
def chatbot():
while True:
user_input = input("You: ")
if user_input.lower() == "hello":
print("Bot: Hi, how are you?")
elif user_input.lower() == "goodbye":
print("Bot: Goodbye! It was nice chatting with you.")
hreak
elif user_input.lower() == "what is your name":
print("Bot: My name is Chatty!")
else:
print("Bot: I didn't understand that. Try again!")
chatbot()
Create a Grade Calculator that calculates the grade based on the user's score. Use if, elif, and else statements to determine the grade.
def grade_calculator():
score = float(input("Enter your score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}")
grade_calculator()
Create a Quiz Game that asks the user a series of questions and determines their score based on their answers. Use if and else statements to check the user's answers and provide feedback.
def quiz_game():
score = 0
questions = [
{"question": "What is the capital of France?", "answer": "Paris"},
{"question": "What is the largest planet in our solar system?", "answer": "Jupiter"},
{"question": "What is the smallest country in the world?", "answer": "Vatican City"},
{"question": "What is the largest living species of lizard?", "answer": "Komodo dragon"},
{"question": "What is the deepest ocean?", "answer": "Pacific Ocean"}
]
for question in questions:
user_answer = input(question["question"] + " ")
if user_answer.lower() == question["answer"].lower():
print("Correct!")
score += 1
else:
print(f"Sorry, the correct answer is {question['answer']}.")
if score == 5:
print("Congratulations, you got a perfect score!")
elif score >= 3:
print("Good job, you scored " + str(score) + " out of 5!")
else:
print("Don't worry, you can try again!")
quiz_game()
Create a countdown timer that counts down from a user-inputted number. Use a for loop to iterate from the inputted number down to 0.
def countdown_timer():
num = int(input("Enter a number: "))
for i in range(num, 0, -1):
print(i)
print("Blast off!")
countdown_timer()
Create a program that generates the Fibonacci sequence up to a user-inputted number. Use a while loop to generate the sequence.
def fibonacci_sequence():
num = int(input("Enter a number: "))
a, b = 0, 1
sequence = [a, b]
while len(sequence) < num:
a, b = b, a + b
sequence.append(b)
print(sequence)
fibonacci_sequence()
Create a game of Hangman where the user has to guess a word by inputting individual letters. Use a for loop to iterate over the word and check if the user's guess is correct.
def hangman():
word = "python"
guessed_letters = []
for letter in word:
while True:
user_guess = input("Guess a letter: ")
if user_guess in guessed_letters:
print("You already guessed that letter!")
elif user_guess == letter:
print("Correct! The letter is in the word.")
guessed_letters.append(user_guess)
hreak
else:
print("Incorrect. The letter is not in the word.")
guessed_letters.append(user_guess)
print("Congratulations! You guessed the word.")
hangman()
Create a program that generates a multiplication table for a user-inputted number.
def multiplication_table():
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
multiplication_table()
Create a Mad Libs game where the user can input words to create a funny story.
def mad_libs():
story = "Once upon a time, there was a __ADJECTIVE__ dragon who lived in a __ADJECTIVE__ cave."
words = {}
while True:
word_type = input("Enter a type of word (adjective, noun, verb, etc.): ")
word = input(f"Enter a {word_type}: ")
words[word_type] = word
if len(words) == 2:
hreak
story = story.replace("__ADJECTIVE__", words["adjective"])
print("Here is your Mad Libs story:")
print(story)
mad_libs()
Create a to-do list app that allows users to add, remove, and view tasks. The app should store the tasks in a file and load them when the app starts.
def load_tasks(filename):
try:
with open(filename, 'r') as f:
tasks = [line.strip() for line in f.readlines()]
return tasks
except FileNotFoundError:
return []
def save_tasks(filename, tasks):
with open(filename, 'w') as f:
for task in tasks:
f.write(task + '\n')
def todo_list_app():
filename = 'todo.txt'
tasks = load_tasks(filename)
while True:
print("To-Do List App")
print("1. Add task")
print("2. Remove task")
print("3. View tasks")
print("4. Quit")
choice = input("Choose an option: ")
if choice == '1':
task = input("Enter a new task: ")
tasks.append(task)
save_tasks(filename, tasks)
elif choice == '2':
task = input("Enter a task to remove: ")
if task in tasks:
tasks.remove(task)
save_tasks(filename, tasks)
elif choice == '3':
print("Tasks:")
for task in tasks:
print(task)
elif choice == '4':
hreak
else:
print("Invalid option. Try again!")
todo_list_app()
Create a student database that stores student information in a file. The program should allow users to add, remove, and view student records.
def load_students(filename):
try:
with open(filename, 'r') as f:
students = [line.strip().split(',') for line in f.readlines()]
return students
except FileNotFoundError:
return []
def save_students(filename, students):
with open(filename, 'w') as f:
for student in students:
f.write(','.join(student) + '\n')
def student_database():
filename = 'students.txt'
students = load_students(filename)
while True:
print("Student Database")
print("1. Add student")
print("2. Remove student")
print("3. View students")
print("4. Quit")
choice = input("Choose an option: ")
if choice == '1':
name = input("Enter student name: ")
grade = input("Enter student grade: ")
students.append([name, grade])
save_students(filename, students)
elif choice == '2':
name = input("Enter student name to remove: ")
for student in students:
if student[0] == name:
students.remove(student)
save_students(filename, students)
hreak
elif choice == '3':
print("Students:")
for student in students:
print(f"{student[0]} - {student[1]}")
elif choice == '4':
hreak
else:
print("Invalid option. Try again!")
student_database()
Create a program that reads a CSV file and outputs the contents to the console.
import csv
def read_csv(filename):
with open(filename, 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
read_csv('example.csv')
Create a program that reads a log file and outputs summary statistics, such as the number of requests, most frequent URL, and average response time.
import collections
def analyze_log(filename):
with open(filename, 'r') as f:
log_entries = [line.strip().split() for line in f.readlines()]
num_requests = len(log_entries)
freq_url = collections.Counter(entry[6] for entry in log_entries).most_common(1)[0]
avg_response_time = sum(int(entry[8]) for entry in log_entries) / num_requests
print(f"Number of requests: {num_requests}")
print(f"Most frequent URL: {freq_url[0]} ({freq_url[1]} times)")
print(f"Average response time: {avg_response_time:.2f} ms")
analyze_log('log.txt')
Create a program that serializes and deserializes Python objects to and from JSON files.
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def serialize_to_json(obj, filename):
with open(filename, 'w') as f:
json.dump(obj.__dict__, f)
def deserialize_from_json(filename):
with open(filename, 'r') as f:
data = json.load(f)
return Person(**data)
person = Person('John Doe', 30)
serialize_to_json(person, 'person.json')
loaded_person = deserialize_from_json('person.json')
print(loaded_person.name) # Output: John Doe
print(loaded_person.age) # Output: 30
Python code for a basic calculator that performs addition, subtraction, multiplication, and division:
def add(num1, num2):
"""Adds two numbers and returns the result."""
return num1 + num2
def subtract(num1, num2):
"""Subtracts two numbers and returns the result."""
return num1 - num2
def multiply(num1, num2):
"""Multiplies two numbers and returns the result."""
return num1 * num2
def divide(num1, num2):
"""Divides two numbers and handles division by zero error."""
if num2 == 0:
return "Error: Cannot divide by zero"
else:
return num1 / num2
def calculator():
"""Runs the calculator program."""
print("Welcome to the Simple Calculator!")
while True:
# Get user input for operation
operation = input("Choose an operation (add, subtract, multiply, divide): ").lower()
# Get user input for numbers
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter numbers only.")
continue
# Perform operation based on user choice
if operation == "add":
result = add(num1, num2)
elif operation == "subtract":
result = subtract(num1, num2)
elif operation == "multiply":
result = multiply(num1, num2)
elif operation == "divide":
result = divide(num1, num2)
else:
print("Invalid operation. Please choose from add, subtract, multiply, or divide.")
continue
# Print the result
print(f"{num1} {operation.upper()} {num2} = {result}")
# Ask user if they want to continue
choice = input("Do you want to perform another calculation? (yes/no): ").lower()
if choice != "yes":
hreak
print("Thank you for using the calculator!")
if __name__ == "__main__":
calculator()
Python code for a number guessing game with some improvements:
import random
def play_game():
"""Runs a single round of the number guessing game."""
# Set difficulty levels (modify as desired)
difficulty_levels = {"easy": (1, 10), "medium": (1, 50), "hard": (1, 100)}
# Get user input for difficulty
while True:
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty in difficulty_levels:
hreak
else:
print("Invalid difficulty. Please choose from easy, medium, or hard.")
# Get the secret number based on difficulty
lower_bound, upper_bound = difficulty_levels[difficulty]
secret_number = random.randint(lower_bound, upper_bound)
# Set number of guesses allowed (adjust based on difficulty)
num_guesses = 5 if difficulty == "easy" else 3
# Start the guessing loop
print(f"I'm thinking of a number between {lower_bound} and {upper_bound}. You have {num_guesses} guesses.")
while num_guesses > 0:
try:
guess = int(input("Guess a number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if guess == secret_number:
print(f"Congratulations! You guessed the number in {num_guesses} attempts.")
hreak
elif guess < secret_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")
num_guesses -= 1
if num_guesses == 0:
print(f"Sorry, you ran out of guesses. The number was {secret_number}.")
# Play the game
while True:
play_game()
# Ask user if they want to play again
choice = input("Do you want to play again? (yes/no): ").lower()
if choice != "yes":
hreak
print("Thank you for playing!")
This program is designed to help you manage and analyze student grades. It offers several features to make grading easier and more efficient:
def calculate_average(grades):
"""Calculates the average grade for a student or the class."""
if not grades:
return 0 # Handle empty grades list
return sum(grades) / len(grades)
def update_student_grades(student_grades):
"""Allows adding new students or updating grades."""
while True:
action = input("Enter 'add' to add a student, 'update' to update grades, or 'done' to finish: ").lower()
if action == 'done':
hreak
elif action == 'add':
name = input("Enter student name: ")
grades = []
while True:
grade_str = input("Enter a grade (or 'done' to finish grades): ")
if grade_str.lower() == 'done':
hreak
try:
grade = float(grade_str)
grades.append(grade)
except ValueError:
print("Invalid grade. Please enter a number.")
student_grades[name] = grades
print(f"Student {name} added successfully.")
elif action == 'update':
name = input("Enter student name to update grades: ")
if name not in student_grades:
print(f"Student {name} not found.")
continue
grades = student_grades[name]
new_grades = []
while True:
grade_str = input("Enter a new grade (or 'done' to finish updates): ")
if grade_str.lower() == 'done':
hreak
try:
grade = float(grade_str)
new_grades.append(grade)
except ValueError:
print("Invalid grade. Please enter a number.")
student_grades[name] = new_grades
print(f"Grades for student {name} updated successfully.")
else:
print("Invalid action. Please choose 'add', 'update', or 'done'.")
def main():
student_grades = {}
while True:
print("\nStudent Gradebook")
print("-" * 20)
print("1. View student grades")
print("2. Update student grades")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
if not student_grades:
print("No students added yet.")
continue
for name, grades in student_grades.items():
average = calculate_average(grades)
print(f"Student: {name}, Average Grade: {average:.2f}")
class_average = calculate_average([grade for grades in student_grades.values() for grade in grades])
print(f"Class Average: {class_average:.2f}")
elif choice == '2':
update_student_grades(student_grades)
elif choice == '3':
hreak
else:
print("Invalid choice. Please choose 1, 2, or 3.")
if __name__ == "__main__":
main()
Python code that gets user input as a string, analyzes it using string methods, and counts vowels and consonants
def count_vowels_consonants(text):
"""Counts the number of vowels and consonants in a text string."""
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHIJKLMNPQRSTVWXYZ'
vowel_count = 0
consonant_count = 0
# Remove non-letter characters (optional)
text = ''.join(char for char in text if char.isalpha())
for char in text:
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1
return vowel_count, consonant_count
def main():
# Get user input
user_text = input("Enter a string: ")
# Analyze the text
text_length = len(user_text)
uppercase_text = user_text.upper()
lowercase_text = user_text.lower()
words = user_text.split()
# Count vowels and consonants
vowel_count, consonant_count = count_vowels_consonants(user_text)
# Print the results
print("\nText Analysis Results:")
print(f" - Number of characters (excluding spaces): {text_length}")
print(f" - Uppercase text: {uppercase_text}")
print(f" - Lowercase text: {lowercase_text}")
print(f" - Number of words: {len(words)}")
print(f" - Vowels: {vowel_count}")
print(f" - Consonants: {consonant_count}")
if __name__ == "__main__":
main()
Pthon program that takes user input and converts it between different data types, handling potential errors with try-except blocks
def convert_data_type(value):
"""Converts the given value to different data types and handles errors."""
try:
# Try converting to integer
int_value = int(value)
print(f"Converted to integer: {int_value}")
return int_value
except ValueError:
pass
try:
# Try converting to float
float_value = float(value)
print(f"Converted to float: {float_value}")
return float_value
except ValueError:
pass
try:
# Try converting to boolean (considering True/False or 1/0)
if value.lower() in ("true", "1"):
bool_value = True
elif value.lower() in ("false", "0"):
bool_value = False
else:
raise ValueError
print(f"Converted to boolean: {bool_value}")
return bool_value
except ValueError:
pass
# If all conversions fail, return the original value as a string
print(f"Value cannot be converted to a numeric data type. Keeping as string: {value}")
return value
def main():
while True:
# Get user input
user_input = input("Enter a value to convert: ")
# Convert the input and handle errors
converted_value = convert_data_type(user_input)
# Ask user if they want to continue
choice = input("Do you want to convert another value? (yes/no): ").lower()
if choice != "yes":
hreak
print("Thank you for using the data type converter!")
if __name__ == "__main__":
main()
Create a program that simulates a bank account system using OOP concepts. The system should allow users to create accounts, deposit and withdraw funds, and check their account balances.
class BankAccount:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds!")
else:
self.balance -= amount
return self.balance
def get_balance(self):
return self.balance
class Bank:
def __init__(self):
self.accounts = {}
def create_account(self, account_number, initial_balance):
self.accounts[account_number] = BankAccount(account_number, initial_balance)
def get_account(self, account_number):
return self.accounts[account_number]
bank = Bank()
bank.create_account("123456", 1000)
account = bank.get_account("123456")
print(account.get_balance()) # Output: 1000
account.deposit(500)
print(account.get_balance()) # Output: 1500
account.withdraw(200)
print(account.get_balance()) # Output: 1300
Create a program that simulates a shopping cart system using OOP concepts. The system should allow users to add and remove items from their cart, update quantities, and calculate the total cost.
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
self.items.remove(item)
def update_quantity(self, item, quantity):
item.quantity = quantity
def calculate_total(self):
total = 0
for item in self.items:
total += item.price * item.quantity
return total
cart = ShoppingCart()
item1 = Item("Apple", 1.00)
item2 = Item("Banana", 0.50)
cart.add_item(item1)
cart.add_item(item2)
cart.update_quantity(item1, 2)
cart.update_quantity(item2, 3)
print(cart.calculate_total()) # Output: 4.50
Create a program that simulates an employee management system using OOP concepts. The system should allow users to create employees, update employee information, and calculate employee salaries.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class EmployeeManagementSystem:
def __init__(self):
self.employees = []
def add_employee(self, employee):
self.employees.append(employee)
def update_employee(self, employee, new_salary):
employee.salary = new_salary
def calculate_total_salary(self):
total = 0
for employee in self.employees:
total += employee.salary
return total
ems = EmployeeManagementSystem()
emp1 = Employee("John Doe", 50000)
emp2 = Employee("Jane Doe", 60000)
ems.add_employee(emp1)
ems.add_employee(emp2)
ems.update_employee(emp1, 55000)
print(ems.calculate_total_salary()) # Output: 115000
Create a program that simulates a traffic simulator using OOP concepts. The system should allow users to create vehicles, update vehicle speeds, and simulate traffic flow.
class Vehicle:
def __init__(self, speed):
self.speed = speed
class TrafficSimulator:
def __init__(self):
self.vehicles = []
def add_vehicle(self, vehicle):
self.vehicles.append(vehicle)
def update_vehicle_speed(self, vehicle, new_speed):
vehicle.speed = new_speed
def simulate_traffic(self):
for vehicle in self.vehicles:
print(f"Vehicle speed: {vehicle.speed} km/h")
simulator = TrafficSimulator()
car = Vehicle(60)
truck = Vehicle(80)
simulator.add_vehicle(car)
simulator.add_vehicle(truck)
simulator.update_vehicle_speed(car, 70)
simulator.simulate_traffic()
Create a program that simulates a game character using OOP concepts. The system should allow users to create characters, update character attributes, and simulate combat.
class Character:
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
def take_damage(self, damage):
self.health -= damage
if self.health <= 0:
print(f"{self.name} has died!")
class Game:
def __init__(self):
self.characters = []
def add_character(self, character):
self.characters.append(character)
def simulate_combat(self, character1, character2):
while character1.health > 0 and character2.health > 0:
character2.take_damage(character1.attack)
character1.take_damage(character2.attack)
game = Game()
player = Character("Player", 100, 20)
enemy = Character("Enemy", 50, 10)
game.add_character(player)
game.add_character(enemy)
game.simulate_combat(player, enemy)