True and False in Python

by: George El., March 2019, Reading time: 2 minutes

In this Post I will describe what is True and False in Python. Then how to use “all” and “any” to combine these values and finally make a function that will check if an ip address is valid.

In python all numbers are True except 0, every object that is not None, every string that is not empty, every list that is not empty, every dictionary that is not empty. We will use the bool function to verify this.

>>> bool(1)
True
>>> bool(2.5)
True
>>> bool(0)
False
>>> bool("123")
True
>>> bool('')
False
>>> bool(None)
False
>>> bool([])
False
>>> bool([1])
True
>>> bool(dict({'a':'1'}))
True
>>> bool(dict())
False
>>> class myObj:
...     pass
...
>>> bool(myObj())
True
>>>

Python has also two other functions, all and any, that given an iterable, can tell you if all the values are True or any of the values is True

>>> all([ 1, 2, 3, 4])
True
>>> all([ 1, 2, 3, 0])
False
>>> any([0, None, '', 1])
True
>>> any(['', None, 0])
False

Now if I have an IP address and I want to know if it is a valid one, I can do it in many ways. We will start with a non pythonic way and then move to a pythonic way. Lets say I have 10.0.0.1. A valid IP address is one that it each octet is >=0 and <=255. The first thing I have to do it split the ip address on “.” using the split function and then check is octet individually using a for loop. If any octet is not >=0 and <=255 I can break the loop and return False

def isValidIP(ip):
    isIP=True
    l = ip.split(".")
    for item in l:
        if not 0<= int(item) <=255:
            isIP=False
            break
    return isIP

so If I call now the function I will get

print(isValidIP("10.0.0.1"))
True 
print(isValidIP("10.0.0.256"))
False

Now there must be a sorter more pythonic way to do this and there is. Instead of using a for loop I can use a list comprehension or the map function.

def isValidIPv2(ip):
    l = ip.split(".")
    l2 = [0<= int(item) <=255 for item in l]
    print(l2)
    return all(l2)

print(isValidIPv2("10.0.0.1"))
print(isValidIPv2("10.0.0.256"))

the output is

[True, True, True, True]
True
[True, True, True, False]
False

I can put everything in a single line

def isValidIPv3(ip):
    return all([0<= int(item) <=255 for item in ip.split(".")])

I can also convert the list comprehension to a generator expression.

def isValidIPv3(ip):
    return all((0<= int(item) <=255 for item in ip.split(".")))
comments powered by Disqus