Codsoft Assignment
Codsoft Assignment
CALCULATOR
def add(x, y):
return x + y
def get_operation_choice():
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'):
if choice == '1':
return add
elif choice == '2':
return subtract
elif choice == '3':
return multiply
else:
return divide
else:
print("Invalid input. Please enter 1, 2, 3 or 4.")
def main():
print("Simple Calculator")
while True:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = get_operation_choice()
result = operation(num1, num2)
print("Result:", result)
break
except ValueError:
print("Invalid input. Please enter numbers only.")
if __name__ == "__main__":
main()
Task 2
PASSWORD GENERATOR
import random
characters = []
if lowercase:
characters.extend(string.ascii_lowercase)
if uppercase:
characters.extend(string.ascii_uppercase)
if digits:
characters.extend(string.digits)
if punctuation:
characters.extend(string.punctuation)
def main():
print("Welcome to the Password Generator!")
while True:
try:
length = int(input("Enter desired password length (minimum 8
characters): "))
if length < 8:
raise ValueError("Password length must be at least 8
characters.")
if __name__ == "__main__":
main()
Task 3
Rock-Paper-Scissors Game
import random
def get_user_choice():
while True:
choice = input("Enter your choice (rock, paper, scissors):
").lower()
if choice in ('rock', 'paper', 'scissors'):
return choice
else:
print("Invalid choice. Please enter rock, paper, or scissors.")
def get_computer_choice():
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "tie"
elif user_choice == 'rock':
if computer_choice == 'scissors':
return "user"
else:
return "computer"
elif user_choice == 'paper':
if computer_choice == 'rock':
return "user"
else:
return "computer"
else:
if computer_choice == 'paper':
return "user"
else:
return "computer"
def play_game():
user_choice = get_user_choice()
computer_choice = get_computer_choice()
winner = determine_winner(user_choice, computer_choice)
if winner == "user":
print("You win!")
elif winner == "computer":
print("You lose.")
else:
print("It's a tie!")
return winner
def main():
user_score = 0
computer_score = 0
play_again = 'y'
if __name__ == "__main__":
main()