r/pythonhelp • • Jun 12 '22

Trying to check if a value is a positive integer, what am I doing wrong? Getting 'True' for all values. Thank you!!!

def isPosInt(val):
    if type(val) == int:
        return True
    else:
        if int(val) >= 0:
            return True
        else:
            return False
        
isPosInt(-5)
3 Upvotes

4 comments sorted by

3

u/MrHyderion Jun 12 '22

Look at what your function does.

It checks whether the variable passed into it is an int -> if yes, it returns true -> if no, it checks whether the variable is >= 0, returning true if yes, and false if no.

So obviously each time you pass an int to this function, it will return true right away without ever checking if it's positive.

2

u/sonnylunadogs Jun 12 '22

Thank you, I am very new to coding so these simple things get me sometimes.

def isPosInt(val):

if type(val) == int and int(val) >= 0:

return True

else:

return False

^ this works perfectly

1

u/MrHyderion Jun 12 '22

Yes, that's the best solution, also easier to read than a nested if. :)

1

u/htepO Jun 12 '22

Alternatively, you could use isinstance() to check if val is an instance of the int class.

Relational operators like == or >= and logical operators like and return boolean True/False that can be returned immediately.

A shorter version of your function would be:

def isint(val):
    return isinstance(val, int) and val >= 0

>>> isint(10) # True and True
True
>>> isint(-10) # True and False
False
>>> isint(0) # True and True
True
>>> isint("python") # False and TypeError
False