一元的坏操作数类型 - :“str”

时间:2016-05-01 02:07:53

标签: python

Python新手,无法弄清楚下面的代码有什么问题。

a = input('input a number: ')
if int(a) >=0:
    print(a)
else:
    print(-a)

输入-2时,输出应为2。

但是,我收到了错误代码:

TypeError: bad operand type for unary-:"str' on print(-a)

有人可以帮忙吗?感谢。

3 个答案:

答案 0 :(得分:4)

尝试:

a = int(input('input a number: '))
if a >=0:
    print(a)
else:
    print(-a)

a = int(input('input a number: '))
print abs(a)

答案 1 :(得分:1)

a = input('input a number: ')
#a at this point is a string, not an integer
if int(a) >=0:
    print(a)
    #you are printing a string, it just happen to look the same as an integer
else:
    print(-int(a))
    #you could do - to an integer, not a string

答案 2 :(得分:-1)

如果您要处理字符串:

replace int with str

print(str(a))