2016-05-01 110 views
0

新的Python和想不出有什麼不對下面的代碼錯誤操作數類型一元 - :「STR」

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) 

誰能幫助感謝

回答

2

嘗試:

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

a = int(input('input a number: ')) 
print abs(a) 
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 
相關問題