## Boolean Values and Expressions

A place where you can post Python-related tutorials you made yourself, or links to tutorials made by others.

### Boolean Values and Expressions

What are They?

There are only two Boolean values. They are True and False. Capitalization is important, since true and false are not Boolean values (remember Python is case sensitive). A boolean expression is an expression that evaluates to a Boolean value. The equality operator, ==, compares two values and produces a Boolean value related to whether the two values are equal to one another.

Code: Select all
`print(5 == 5) # Outputs Trueprint(5 == 6) # Outputs False`

Boolean values are not strings!
It is extremely important to realize that True and False are not strings. They are not surrounded by quotes. They are the only two values in the data type bool.

Here are the Most Common Comparison Operators:

Code: Select all
`x != y               # x is not equal to yx > y                # x is greater than yx < y                # x is less than yx >= y               # x is greater than or equal to yx <= y               # x is less than or equal to y`

Logical Operators
There are three logical operators: and, or, and not. The meaning of these operators is similar to their meaning in English.

Examples:

x > 0 and x < 10 is true only if x is greater than 0 and at the same time, x is less than 10.

n % 2 == 0 or n % 3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or divisible by 3. In this case, one, or the other, or both of the parts has to be true for the result to be true.

Finally, the not operator negates a boolean expression, so not x > y is true if x > y is false, that is, if x is less than or equal to y.

Common Mistake!

There is a very common mistake that occurs when programmers try to write boolean expressions. For example, what if we have a variable number and we want to check to see if its value is 5,6, or 7. In words we might say: “number equal to 5 or 6 or 7”. However, if we translate this into Python, number == 5 or 6 or 7, it will not be correct. The or operator must join the results of three equality checks. The correct way to write this is number == 5 or number == 6 or number == 7. This may seem like a lot of typing but it is absolutely necessary. You cannot take a shortcut.

Uses for Boolean

Boolean functions are always used in while loops.
They are always used in if statements.

These things will be commonly used in all Python programs, so Boolean functions must be known.
Occupation GCSE Computing Student.
Languages Python 3, JavaScript, HTML, Batch.
python-forum.org is epic!

alext6453

Posts: 4
Joined: Tue Feb 19, 2013 12:57 pm
Location: Hertfordshire, England.

### Re: Boolean Values and Expressions

alext6453 wrote:There is a very common mistake that occurs when programmers try to write boolean expressions. For example, what if we have a variable number and we want to check to see if its value is 5,6, or 7. In words we might say: “number equal to 5 or 6 or 7”. However, if we translate this into Python, number == 5 or 6 or 7, it will not be correct. The or operator must join the results of three equality checks. The correct way to write this is number == 5 or number == 6 or number == 7. This may seem like a lot of typing but it is absolutely necessary. You cannot take a shortcut.

Actually, there is a shortcut here.

Code: Select all
`number == 5 or number == 6 or number == 7`

is equivalent to:

Code: Select all
`number in (5, 6, 7)`

Another useful short cut for boolean operators is to chain them.

Code: Select all
`5 <= number and number <= 7`

is equivalent to:

Code: Select all
`5 <= number <= 7`

Also note that a boolean operator is not always needed. If you are in a context requiring a boolean operator (such as an if statement), Python will attempt to convert whatever you put there into either True or False. Numbers are False if they are zero, and are True otherwise. Sequences (strings, lists, tuples) are False if they have zero length, and are True otherwise. Dictionaries also convert to False if empty. Instances of user created classes are always True by default, but this can be overridden by overloading the __nonzero__ method or the __len__ method.
Due to the reasons discussed here we will be moving to python-forum.io on October 1st, 2016.
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
ichabod801

Posts: 688
Joined: Sat Feb 09, 2013 12:54 pm
Location: Outside Washington DC

### Re: Boolean Values and Expressions

As well as what ichabod said, I'd like to delve deeper into why
Code: Select all
`if x == 'a' or 'b':`

doesn't work.

First, the idea of short circuit logic needs to be covered. This means that when you have x() and y() if x() returns boolean False, then y() isn't evaluated. If y() has side effects, this matters (good code uses side effects sparingly, but sometimes it happens). This is done mostly for efficiency reasons, since the value of y() doesn't matter in the previously mentioned expression. There is a similar result for or. The expression x() or y() returns True immediately if x() is True.

Secondly, what does the expression False or True evaluate to? Well, True of course! How about False or 7? It evaluates, possibly surprisingly, to 7! What about False or []? It evaluates to the empty list on the right. How about [1, 2, 4] or 7? The list on the left. Python's and and or return the last part evaluated, whatever the object is, and not to a boolean conversion of that value. Here is a common-ish trick
Code: Select all
`def cleanup_name(name):    return name.capitalize() or 'User'`

If the name variable is passed in from raw_input(), and the user entered nothing, then their name will default to "User" and otherwise it will capitalize their name. This is also often done for default None arguments in functions.

Now back to the original expression. We might think that the 'a' or 'b' acts like a list, and the equal sign gets distributed like a multiplication in math. This is not the case, using unnecessary parenthesis (but to clarify things here), it is actually equivalent to:
Code: Select all
`if (x == 'a') or ('b'):`

As we can clearly see, the x comparison gets evaluated to either True or False and then if it's False, ('b') gets evaluated, and that's always boolean True. So, the expression x == 'a' or 'b' always evaluates to True. An unfortunate programmer may test their own code for 'a' and 'b', find that both work, and be satisfied without realizing that it never fails. (Always test failure!)

alext6453 wrote:Boolean functions are always used in while loops.
They are always used in if statements.

Strictly speaking, you talked about operators and not functions, and if you're using a function as part of an if or while it needn't be strictly boolean. You could have a condition like this
Code: Select all
`x = 7while x:    print x    x -= 1`

(This could easily be changed to be a function, or generator.) You could also do it with a list, popping from the end until the list is empty, or anything like that.

I make this distinction because although often times these differences do not matter, sometimes they do, and knowing the proper terminology can be very helpful for efficient communication in very technical situations.
Due to the reasons discussed here we will be moving to python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

micseydel

Posts: 3000
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA