A number divided by a string is not a number

duration = inputScriptLine.split(' ', 1)[1]
if type(duration) == str:
    print '    Error: Sleep duration "' + duration + '" is not numeric'

SLEEP 50, I get Error: Sleep duration "50" is not numeric

I'm not too worried about why, I just want to know how I can code to SLEEP 50be valid, but SLEEP APNOEAnot.

+4
source share
5 answers

Use isdigit () :

if not duration.isdigit():
    print 'Error: Sleep duration "' + duration + '" is not numeric'

It will check if all characters are in durationnumbers or not.

+5
source

If you want to accept more than just ints, you should use float:

def is_numeric(s):
    try:
        float(s)
        return True
    except ValueError:
        return False


duration = inputScriptLine.split(' ', 1)[1]
if not is_numeric(duration):
     print('    Error: Sleep duration {} is not numeric'.format())

float("1.0"), float("1"), float("1.5")Etc. all will return True, but int ("1.0"), int("1.5")etc. will also return False, if you are really looking for numerical input, it will be wrong.

, , f > 0:

def is_positive_numeric(s):
    try:
        f = float(s)
        return f > 0
    except ValueError:
        return False
+3
try:
    duration = int(duration)
except:
    pass

int, , .

The DeveloperXY solution is cleaner, but if you want to use the value as an int later, my solution is useful.

+2
source

You check if the input is a string. It will be ... you just used the command splitfor the string.

You need to check if the string contains only numeric characters, s .isdigit().

Please note that this will not accept negative inputs, but you do not want this time.

So your new code:

duration = inputScriptLine.split(' ', 1)[1]
if not duration.isdigit():
    print 'Error: Sleep duration "' + duration + '" is not numeric'
+1
source
duration = inputScriptLine.split(' ', 1)[1]
try:
    duration = int(duration)
except ValueError:
    print '    Error: Sleep duration "' + duration + '" is not numeric'
+1
source

Source: https://habr.com/ru/post/1629551/


All Articles