0

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

Luci5274
  • 3
  • 2

3 Answers3

1

The abs function expects an int, but in the first code block you pass it a string. In the second code block, you convert the string to an int -- this is missing in the first code block.

So combine the two:

ival = abs(int(rawstr))

A second issue is that isnumeric is a method for strings, not for numbers, so don't use that as you did in the first code block, and do ival >= 0 as if condition.

So:

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

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

The downside is that with abs you really have a non-negative number and lost the sign.

Merge the two parts and do:

rawstr = input('enter a number: ')
try:
    ival = int(rawstr)
    print('nice work')
except:
    print('not a number')
    # Here you can exit a loop, or a function,...
trincot
  • 317,000
  • 35
  • 244
  • 286
0

you may change the abs function to the int function to convert the input string to an integer

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

if isinstance(ival, int) and ival >= 0:
    print('nice work')
else:
    print('not a number')
Lakshitha Samod
  • 383
  • 3
  • 10
  • isnumeric() only returns True for positive integers, so we need to check if ival is an instance of an integer and is greater than or equal to 0 to consider it a valid number. – Lakshitha Samod Mar 04 '23 at 05:54
0

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')
DilLip_Chowdary
  • 841
  • 4
  • 18