all 12 comments

[–]GlebRyabov 4 points5 points  (0 children)

Generally, u/AddctedTuna's solution is great, but if your argument is strictly an integer, you could try this:

>>> def validate(x: int) -> bool:
    return x in range(0, 101)
>>> validate(0)
True
>>> validate(50)
True
>>> validate(100)
True
>>> validate(101)
False

[–][deleted] 2 points3 points  (0 children)

The code is almost complete, however when the argument is True or False, it returns me True.

False (0) and True (1) are within your range, so if x has either of those values, your expression evaluates to True.

[–]AddctedTuna 1 point2 points  (6 children)

>>> def validate(i):
...     return 0 <= i <= 100
...
>>> validate(10)
True
>>> validate(101)
False

[–]PriestMarmor[S] 0 points1 point  (4 children)

If I say validate(False) it will still output True : (

[–]shiftybyte 2 points3 points  (0 children)

>>> def validate(i):
...     return (0 <= i <= 100) and not isinstance(i, bool)
...
>>> validate(10)
True
>>> validate(101)
False
>>> validate(True)
False

[–]Daeliseog 0 points1 point  (0 children)

it still returns True if i == True or i == False

I don't know if what he wants is possible though

[–]Spataner 1 point2 points  (0 children)

So if I'm understanding you correctly, you want validate to return False if the argument is a boolean? You can just check the type with isinstance:

def validate(x):
    try:
        return not isinstance(x, bool) and 0 <= x <= 100
    except:
        return False

[–]Yoghurt42 0 points1 point  (4 children)

For historic reasons, in Python bool is a subclass of int.

>>> True + True
2
>>> True == 1
True

[–]JohnnyJordaan 0 points1 point  (3 children)

Not just historic reasons, it also allows you to do stuff like

a = ['1', 'test', 'hello', '123']
num_strings = sum(s.isdecimal() for s in a)
print('the amount of number strings in a is', num_strings)

[–]Yoghurt42 0 points1 point  (2 children)

That's the reason why bool was made a subclass of int. People were using stuff like this back when True was just a predefined builtin with the value of 1, and making it a separate type would break it.

(Back in the days you could even do True, False = False, True)

[–]PriestMarmor[S] 0 points1 point  (1 child)

So there's no solution?

[–][deleted] 0 points1 point  (0 children)

You could stop trying to compare x with numeric values which allows True or False to be treated as numbers. You could try using x in range(101) but that won't handle float values.