uTypeError: unsupported operand type(s) for -: 'str' and 'str'

后端 未结 2 797
难免孤独
难免孤独 2020-12-12 05:29

I get this error:

uTypeError: unsupported operand type(s) for -: \'str\' and \'str\'

From this code:

print \"wha         


        
相关标签:
2条回答
  • 2020-12-12 06:12

    raw_input() returns a string, so basically you end up with this:

    print '20'-'11'
    

    Since you cannot subtract one string from another, you need to convert them to numbers first.

    Try this:

    z = float(raw_input())
    ...
    f = float(raw_input())
    

    Secondly, use descriptive variable names instead of x, y, z and f, so something like:

    age = float(raw_input())
    ...
    firstPlaneTravelAge = float(raw_input())
    
    print age-firstPlaneTravelAge, ...
    

    Also note that this code has no validation, it will crash if the user enters something which isn't a number.

    0 讨论(0)
  • 2020-12-12 06:35

    Your variables z and f are strings. Python doesn't support subtracting one string from another string.

    If you want to display a number, you're going to have to convert them to either floats or integers:

    print int(z) - int(f),"years ago",x, " first took an airplane."
    

    The reason these are strings in the first place is because raw_input always returns a string.

    0 讨论(0)
提交回复
热议问题