Home > Mobile >  Return type in Python, why is it not working without a variable?
Return type in Python, why is it not working without a variable?

Time:01-10

Why is this not working:

def ice_cream(order):
    if order == ("one"):
        return 2.50
    if order == ("two"):
        return 5.00
    if order == ("three"):
        return 80
    else:
        print ("invalid")

ice = input("enter")


ice_cream(ice)

but this one is working:



def ice_cream(order):
    if order == ("one"):
        return 2.50
    if order == ("two"):
        return 5.00
    if order == ("three"):
        return 80
    else:
        print ("invalid")

ice = input("enter")

wtf = ice_cream(ice)
print(wtf)

CodePudding user response:

I think it's working, but you don't see the result because you forgot to print the result. Try changing this line ice_cream(ice) to this print(ice_cream(ice)). You don't see the output returned by a method call unless you print it.

CodePudding user response:

The function ice_cream returns one of the values 2.5, 5.0, or 80 to the caller. (Unless the input is invalid.) I suppose you entered a valid input when you tried to run your program. Suppose you entered one. Then,

  • in your first code, the function is called, the value 2.5 is returned, but never further used (not even stored for later use).
  • in your second code example, the function is called and its return value 2.5 is stored in the variable wtf. Then you print wtf and everything is fine.

So it's not about the type of the returned variable, but about the fact that Python will not print the returned variable without you demanding it.

  •  Tags:  
  • Related