#

Tuesday, February 18, 2025

Boolean Logic of Python for Network Engineers

There is a function in Python called "Bool" function, which we can use to check the "True" or "False" status of a variable. What it actually does is that it checks whether the variable is empty itself or not.

You can clearly see that logic from following snippet.

String1 consists of some characters (aka not empty) hence the bool function shows the output as true but since String2 is empty, it opts out false.

No matter the variable type, this is how it behaves, meaning it can be a List, Tuple, Dict or Set, it is like this.

Apart of bool function, there are Logical Operators / Gates which contributes to Boolean logic.

Python has following 3 logical operator types.



AND

This checks whether all the values are true or not.
Following example code shows how this logic works,










Since both values are true, the output will be like the following.




When I change the version1 to be 12 or something it gets the other output.

OR

Let's say If I mistakenly used OR operator for the above example  and change the version1 to be 12 like the following, which will help us understand how it works,










The output will be like the following,




It means that, if one of the items are true, that's enough to make the operator opt outs true.

NOT

Let's see the following practical example to understand this logic.









This means if I enter a range of IP addresses, it will check against the values in the List and opt out the corresponding output. 







Now by adding the NOT operator, we can negate the answers, which will obviously make no sense but for the sake of understanding how it works, lets try it.





No comments:

Post a Comment