The most common answer is:
num1 = int(input("What is the first number?: "))
num2 = int(input("What is the second number?: "))
def add(n1, n2):
result = n1 + n2
print(str(n1) + " + " + str(n2) + " = " + str(result))
def subtract(n1, n2):
result = n1 - n2
print(str(n1) + " - " + str(n2) + " = " + str(result))
def multiply(n1, n2):
result = n1 * n2
print(str(n1) + " * " + str(n2) + " = " + str(result))
def invalid():
print("An invalid option was selected")
operation = input("Choose an operation (add, subtract, multiply): ").lower()
if operation == "add":
add(num1, num2)
elif operation == "subtract":
subtract(num1, num2)
elif operation == "multiply":
multiply(num1, num2)
else:
invalid()
In this version:
- Functions now take parameters, making them reusable for different numbers, not just
num1
andnum2
. - The input prompt for choosing an operation converts the response to lowercase to ensure case-insensitive comparison.
- Standard ASCII quotation marks are used for compatibility with Python syntax.
- The variable
Operation
has been changed to lowercase (operation
) to follow Python naming conventions for variables.