2016-05-01 14 views
0

Neu bei Python und kann nicht herausfinden, was unten mit dem Code falschBad Operandtyp für einstellige -:. "Str‘

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

Wenn -2 eingeben, sollte die Ausgabe seinen 2.

Allerdings habe ich einen Fehlercode:.

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

Kann mir jemand helfen Danke

Antwort

2

Versuch:

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

oder

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 
Verwandte Themen