0

I'm currently learning Python, and don't know a whole lot- so I need somebody experienced to help me out here.

The code is this:

usernum = input('Enter a number, Ill determine if its pos, neg, OR Zero.')
if usernum < 0:
    print("Your number is negative.")
if usernum > 0:
    print("Your number is positive.")
if usernum == 0:
    print("Your number is zero.")

The error is this:

Traceback (most recent call last):
  File "C:\Users\Admin\Documents\Test.py", line 2, in <module>
    if usernum < 0:
TypeError: '<' not supported between instances of 'str' and 'int'
  • `usernum` is a string. Make it an int with `int(usernum = input('Enter a number, Ill determine if its pos, neg, OR Zero.'))` – Patrick Haugh Apr 09 '17 at 22:17
  • http://stackoverflow.com/questions/379906/parse-string-to-float-or-int - don't forget about floats too. – stdunbar Apr 09 '17 at 22:23

2 Answers2

1

Try:

usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
if usernum < 0:
    print("Your number is negative.")
if usernum > 0:
    print("Your number is positive.")
if usernum == 0:
    print("Your number is zero.")

input(...) creates strings, so you need to make that string an integer by making it go through int(...). In addition I'd suggest switching you're ifs into if, elif and else:

usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
if usernum < 0:
    print("Your number is negative.")
elif usernum > 0:
    print("Your number is positive.")
else:
    print("Your number is zero.")

It's not a big deal, but this way you're only executing code you actually need. So, if usernum is less than 0 then the next clauses aren't evaluated. Finally, you could consider adding user input error correction:

usernum = None
while usernum is None:
    try:
        usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
    except ValueError as ex:
        print("You didn't enter an integer. Please try again.")
if usernum < 0:
    print("Your number is negative.")
if usernum > 0:
    print("Your number is positive.")
if usernum == 0:
    print("Your number is zero.")
André C. Andersen
  • 8,955
  • 3
  • 53
  • 79
0

Change your first line to

usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))

As you had it, usernum is a string value, since input() always returns strings in Python 3.x, and you were trying to compare it to integers. So convert it to an integer first. I did this by surrounding the input call with an int() typecast.

Note that this will raise an error if the user types in something other than an integer. This can be dealt with by exception handling, which is probably beyond you right now.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50