问题
Here is my code:
def calculator(value1,value2):
function=input("Function?")
if function=="*":
return value1*value2
if function=="/":
return value1/value2
if function=="+":
return value1+value2
if function=="-":
return value1-value2
a=float(input("value 1:"))
b=float(input("value 2:"))
calculator(a,b)
print(calculator(a,b))
Output on Python Shell
value 1:5
value 2:5
Function?/
Function?/
1.0
So im just wondering why it asks for input for function twice, not once. This is probably a stupid question but thanks for answering.
回答1:
These two lines are causing your problem:
calculator(a,b)
print(calculator(a,b))
You're calling calculator
twice, so it's asking you for input twice.
To fix your code, just store the result of calculator(a, b)
in a variable and then print it out:
result = calculator(a, b)
print(result)
回答2:
You're asking Python to print(calculator(a,b))
- this means Python has to evaluate the function twice. If you want to only input once, store calculator(a,b)
in a variable and print that variable.
来源:https://stackoverflow.com/questions/14302085/simplepython-asks-for-input-twice