Learn how to create a simple basic calculator using Python programming language Boost your programming skills and optimize your code for search engines with our expert tips and . Get the complete code and step-by-step instructions for building your own calculator
This code takes in user input for the calculation operation to be performed and the two numbers to be used. It then uses an if-elif block to perform the calculation based on the operator entered and returns the result. If an invalid operator is entered, it returns an error message.
CODE:-
def calculate():
#Take input from the user
opt = input("Please enter the operation you would like to perform (+, -, *, /): ")
first_number = float(input("Please enter the first number: "))
second_number = float(input("Please enter the second number: "))
# Perform the calculation based on the operator entered
if opt == "+":
result = first_number + second_number
elif opt == "-":
result = first_number - second_number
elif opt == "*":
result = first_number * second_number
elif opt == "/":
result = first_number / second_number
# If an invalid operator is entered, return an error message_number
else:
return print("You have entered an invalid operator. Please enter a valid operator (+, -, *, /).")
# Return the result
return result
# Call the function to start the calculator
print(calculate())
Output:-
Please enter the operation you would like to perform (+, -, *, /): +
Please enter the first number: 12
Please enter the second number: 14
26.0