Skip to content

Instantly share code, notes, and snippets.

@OshekharO
Created June 14, 2024 07:08
Show Gist options
  • Save OshekharO/6b4b9ef05c29d86a655f09325ade3df2 to your computer and use it in GitHub Desktop.
Save OshekharO/6b4b9ef05c29d86a655f09325ade3df2 to your computer and use it in GitHub Desktop.
Basic python script for performing addition, subtraction, multiplication, percentage calculation, and division
def add(x, y):
"""Returns the sum of x and y."""
return x + y
def subtract(x, y):
"""Returns the difference of x and y."""
return x - y
def multiply(x, y):
"""Returns the product of x and y."""
return x * y
def calculate_percentage(x, y):
"""Returns the percentage of x in y."""
return (x / y) * 100
def divide(x, y):
"""Returns the result of dividing x by y (handles division by zero)."""
if y == 0:
print("Error: Cannot divide by zero.")
return None
return x / y
def main():
print("Welcome to the Multifunction Calculator!")
while True:
# Get user input for operation
operation = input("Choose an operation (+, -, *, %, /): ")
# Get user input for numbers
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ValueError:
print("Invalid input. Please enter numbers only.")
continue
# Perform operation based on user choice
if operation == "+":
result = add(num1, num2)
print(f"{num1} + {num2} = {result}")
elif operation == "-":
result = subtract(num1, num2)
print(f"{num1} - {num2} = {result}")
elif operation == "*":
result = multiply(num1, num2)
print(f"{num1} * {num2} = {result}")
elif operation == "%":
result = calculate_percentage(num1, num2)
print(f"{num1} is {result}% of {num2}")
elif operation == "/":
result = divide(num1, num2)
if result:
print(f"{num1} / {num2} = {result}")
else:
print("Invalid operation. Please choose +, -, *, %, or /.")
choice = input("Do you want to perform another calculation? (y/n): ")
if choice.lower() != "y":
break
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment