Sure, here's the Python code for a simple calculator:
python
Copy code
# Define the function for addition
def
add
x, y
):
return
x + y
# Define the function for subtraction
def
subtract
x, y
):
return
x - y
# Define the function for multiplication
def
multiply
x, y
):
return
x * y
# Define the function for division
def
divide
x, y
):
if
y ==
return
"Error! Division by zero!"
else
return
x / y
# Print the menu options
"Select operation:"
"1. Addition"
"2. Subtraction"
"3. Multiplication"
"4. Division"
# Ask the user to choose an operation
choice =
input
"Enter choice (1/2/3/4): "
# Ask the user to enter two numbers
num1 =
float
input
"Enter first number: "
))
num2 =
float
input
"Enter second number: "
))
# Perform the selected operation
if
choice ==
'1'
"Result:"
, add(num1, num2))
elif
choice ==
'2'
"Result:"
, subtract(num1, num2))
elif
choice ==
'3'
"Result:"
, multiply(num1, num2))
elif
choice ==
'4'
"Result:"
, divide(num1, num2))
else
"Invalid input"
This code defines four functions for addition, subtraction, multiplication, and division. Then, it provides a menu for the user to choose which operation they want to perform. After the user selects an operation and enters two numbers, the code performs the selected operation and displays the result. If the user selects division and enters 0 as the second number, the code handles the division by zero error gracefully.