kuan
kuan

Reputation: 455

Simple:Python asks for input twice

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.

Upvotes: 0

Views: 5904

Answers (2)

Volatility
Volatility

Reputation: 32300

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.

Upvotes: 2

Blender
Blender

Reputation: 298106

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)

Upvotes: 5

Related Questions