What did I do wrong in this basic python code?

I'm testing out if statements and I encountered this dilemma. I don't understand what I did wrong, and why it expects a string instead of an integer. Here's my code.

# If the entered age was over 21 print "have a drink" otherwise print the other one.
age = input(int("what's your age?:\n\t"))
if age >= 21 :
    print("have a drink")
    print("you're just a lad!")

1 answer

  • answered 2018-03-13 21:21 Barmar

    When you have nested function calls, they're executed from the inside out, with each result serving as the parameter to the next one that contains it. So:

    age = input(int("what's your age?:\n\t"))

    is equivalent to:

    temp = int("what's your age?:\n\t")
    age = input(temp)

    When you write it this way, you can see that the parameter being given to input() is the integer that was returned by int(). In addition, the argument you gave to int() is not something that can be meaningfully converted to an integer.

    The correct syntax is:

    age = int(input("what's your age?:\n\t"))

    This calls input() first, then converts the response to an integer.