问题
Is this an efficient calculator in Python?
def calculator():
print("\nBasic Calculator.\n")
num_1 = input("Enter your first number: ")
operation = input("Enter your operation: ")
num_2 = input("Enter your second number: ")
if operation == ("+"):
sum = float(num_1) + float(num_2)
print ("The answer is:",(sum))
elif operation == ("-"):
sum = float(num_1) - float(num_2)
print ("The answer is:",(sum))
elif operation == ("*"):
sum = float(num_1) * float(num_2)
print ("The answer is:",(sum))
elif operation == ("/") and num_2 == ("0"):
print ("\nYou cannot divide by zero.")
elif operation == ("/"):
sum = float(num_1) / float(num_2)
print ("The answer is:",(sum))
else:
print("Invalid Operation.")
restart = input("\nDo you want to enter another equation? Yes or No?").lower()
if restart == ("yes"):
calculator()
else:
print ("\nEnding Program.")
quit()
calculator()
回答1:
You can use eval()
a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))
0.5
Handle shenanigans by users:
a = 1
b = 0
operation = '/'
try:
print(eval(f'{a} {operation} {b}'))
except Exception as exp:
print(exp)
回答2:
Here is another basic example:
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
try:
x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
if sign == '0':
break
else:
print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
print("Something went wrong, check your input")
回答3:
It's decent, but reviews of working code belong on CodeReview.SE, not here.
- Call the result variable
result
instead ofsum
, that obviously only is meaningful for addition. - As per AlexanderLekontsev's answer, you don't need a huge big
if...else
ladder that always computesresult
and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and defaultarg2=None
, that way you can handle unary functions. - You're assuming the user types in valid floats in response to
num_1
,num_2
. But what if they press return? or typepi
ore
? or 'help' or:-D
etc. You should catch the exceptionValueError: could not convert string to float
and display the user's invalid input back to them, "expected a number"(/"operator").- You only need
num_2
ifoperation
is a binary not a unary operation, but future stuff likesqrt
, log, log10, trigonometrics (sin, cos, tan
), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence. - Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal
7e8
and float/general/exponential notation7e8
? You might need multipletry...except
clauses. You might add aHEX
mode in future. But then you'll need to generalize fromnum1
to sayarg1
, and ifarg1
==HEX
then enable(/toggle) hex mode, and recurse/loop.
- You only need
- Suggest printing
print("Invalid Operation: must be +,-,*,/,...")
, this actually tells the user which operations are legal. So:%
isn't, neither is^
, neither islog
,cos
,sqrt
etc. - So if you implement the above, you can support things like
e^x
- Supporting parentheses would require recursion.
回答4:
Try this:
def calculate(num1, num2, operator):
operator = operator.strip()
if operator.strip() in ['+', '-', '*', '/']:
if operator == '/' and eval(num2) == 0:
return None
try:
result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
except:
return ""
return result
num1 = '3'
num2 = '5'
operator = '+'
result = calculate(num1, num2, operator)
if result == '':
print('Wrong expression !')
elif result == None:
print('Dive bye zero !')
else:
print(f'The answe is {result} !')
回答5:
Your code is alright but we can improvise by using eval()
print(" Basic Calculator ")
i = ""
while i != 'exit':
i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
print(eval(i))
回答6:
Here is a very clean and short calculator script:
num1 = float(input("Enter a number: "))
op = (input("Enter an operation: "))
num2 = float(input("Enter another number: "))
if op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "^":
print(num1 ** num2)
else:
print("error, you did not enter a supported operation")
Also if you were wondering ** means ^ or to the power of.
来源:https://stackoverflow.com/questions/62381867/is-this-an-efficient-calculator-in-python