Simple:Python asks for input twice

风流意气都作罢 提交于 2019-12-11 14:34:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!