Search code examples
python-3.xnegative-numbernegative-integer

negative numbers in python


im trying to get this

rawstr = input('enter a number: ')
try:
    ival = abs(rawstr)
except:
    ival = 'boob'

if ival.isnumeric():
    print('nice work')
else:
    print('not a number')

to recognize negative numbers, but i cant figure out why it always returns 'is not a number' no matter what the input is

the original purpose of this was a learning excercise for try/except functions but i wanted it to recognise negative numbers as well, instead of returning 'is not a number' for anything less than 0

rawstr = input('enter a number: ')
try:
    ival = int(rawstr)
except:
    ival = -1

if ival > 0:
    print('nice work')
else:
    print('not a number')

^ this was the original code that i wanted to read negative numbers


Solution

  • Python inputs are strings by default, we need to convert them to relevant data types before consuming them.

    Here in your code:

    at the line ival = abs(rawstr), the rawtr is always a string, but abs() expects an int type.

    So you will get an exception at this line, so if ival.isnumeric() always receives ival as boob which was not a numeric, so you're getting not a number output.

    Updated code to fix this:

    rawstr = input('enter a number: ')
    
    try:
        ival = str(abs(int(rawstr)))
    except:
        ival = 'boob'
    
    if ival.isnumeric():
        print('nice work')
    else:
        print('not a number')