Introduction to Python Programming. Section 6. Boolean Values, Functions, Expressions, and Variables
In this section you will learn:
- About Boolean values and Boolean functions.
- About Boolean expressions and Boolean variables.
- How to use comparison operators for numbers and text strings.
- About the Boolean operations and, or, not and their truth tables.
- How conditions and the while loop work with Boolean values.
- How to calculate the value of π using the Monte Carlo method.
- How to use the range function with the for loop.
Python has a built-in data type bool to represent Boolean values. These values are sometimes called truth values or logical values. In case you wonder where the name came from, George Boole (1815-1864) was an English mathematician who introduced the so-called Boolean algebra in his 1854 book The Laws of Thought. At that time, the Boolean algebra was merely an abstract theory without obvious practical applications. One hundred years later, it became the fundamental framework of computer science.
In Python, Boolean values and variables are most often used in conditions as well as in the
while loop. A variable of type bool can have two values, True or False. Once such a
value is assigned to a variable, the variable becomes a Boolean variable:
By Boolean functions we mean functions returning either True or False. Python has built-in
Boolean functions – for example, in Subsection 5.11 you learned about the function
isinstance(var, T) which returns True if the variable var has type T and False
The Numpy library which you know well from Section 2 provides (among others) a Boolean
function equal which compares two arrays elementwise, and returns an array of Boolean
And last, you can easily define your own Boolean functions. For example, the following
function divisible(a, b) returns True if a is divisible by b and False otherwise:
Expressions which evaluate to True or False are called Boolean expressions. There are many
types of such expressions. Let’s begin with comparisons between numbers:
Of course one can compare numerical variables as well:
The modulo operator % can be used to check whether a number is even,
Boolean expressions involving numbers or numerical variables mostly contain the following comparison operators:
|>=||greater than or equal to|
|<=||less than or equal to|
|!=||not equal to|
|<>||not equal to (same as !=)|
A common source of confusion for novice programmers is the difference between the == and
= operators. The comparison operator == returns True or False and it is used to compare two
values and determine if they are equal:
The assignment operator = is used to assign a value to a variable, and it does not return
Text strings can be compared using the same operators that are used for numbers.
Since you know that Python is case-sensitive, the following result will not surprise
But the result of this comparison may be a bit surprising:
Python compares strings using the ASCII codes of the characters. Since the ASCII code of the
letter ’M’ is
and the ASCII code of ’F’ is
the outcome of ’Monday’ > ’Friday’ is the same as the outcome of 77 > 70 which is True.
The results of Boolean expressions are Boolean values True or False. They can
be stored in variables which then automatically become Boolean variables. For
One may need a bit of time to get used to this syntax, but it makes perfect sense. Above, a <
1 is a Boolean expression which evaluates to False, and this Boolean value is then assigned
to the variable result. Here is another example:
Here, the Boolean expression 169 % a == 0 evaluates to True because 169 is divisible by 13. The value True is then assigned to the variable result.
When solving real-life problems, we often need to check two or more logical expressions simultaneously. For example, consider the simple task of checking whether three real numbers a, b, c can represent the lengths of the sides of a triangle:
Clearly, all three values must be greater than zero:
Furthermore, the three values also need to satisfy the triangle inequality:
Here, the text string enclosed in triple quotes is called docstring. We will talk about docstrings
in more detail when we will discuss functions in Section 8.
As you can see, the logical operations and and or indeed are useful. And there is one more – not. Now let us revisit them one by one, starting with logical and.
If A and B are Boolean expressions, then A and B is True only if both A and B are True.
Otherwise it is False. Here is an example:
Here both v1 and v2 are True, so v1 and v2 is True. Let’s look at one additional
Here v1 is True and v2 is False, therefore v1 and v2 is False.
A table that summarizes the outcome of A and B for all possible combinations of the Boolean inputs A and B is called truth table. Here is how it looks for the and operator:
|A||B||A and B|
If A and B are Boolean expressions, then A or B is True if at least one of A, B is True. It is
False if both A, B are False. An example:
Here v1 is False and v2 is True, therefore v1 or v2 is True. Another example:
Here both v1 and v2 are False, therefore v1 or v2 is False.
The truth table of the or operator:
|A||B||A or B|
Negation not is a logical operation that changes the value of a Boolean expression from
True to False and vice versa:
Here v1 is False, therefore not v1 is True.
The truth table of the not operator is very simple:
Conditions will be discussed in more detail in Section 10 and the while loop in Section 11.
But we would like to mention here that both conditions and the while loop are based on
Booleans. For example, the if-else statement can accept a Boolean value True which
makes the condition automatically satisfied:
It is hard to think about a meaningful use of that. But passing a Boolean variable
(named, say, DEBUG) can be used to turn on or off debug prints throughout your
Typing while True is a popular way to imitate the do-while or repeat-until loops
which are not present in Python. The keyword break is then used to exit the loop. For
example, the following short program will keep asking the user to enter his age until the user
enters a positive integer:
And of course, the most frequent case is using Boolean expressions. For example, the
following condition will report whether a number is divisible by 10 or not:
The Monte Carlo method is a popular method of scientific computing. Its idea is to employ a
large number of random values to calculate approximately results that are difficult or
impossible to obtain exactly. Sounds complicated? On the contrary! Monte Carlo methods are
simple, and they leave all the heavy lifting to the computer to do. Their drawback is that
usually they are very computationally expensive. To illustrate this, let’s use a Monte Carlo
method to calculate the value of π!
Fig. 52 shows a unit square (0, 1) × (0, 1):
The red part is a quarter-circle whose area is C = πr2∕4 = π∕4. The area of the entire square is A = 1. We will shoot a large number N of random points into the square. We will count the number I of points which lie inside the quarter-circle. Then the ratio I : N will be approximately the same as C : A. Hence
We will use the Random library that you know from Subsection 2.16:
import random as rn
# Number of points:
N = 100000
# Number of points inside the circle:
I = 0
# Generate N random points:
for i in range(N):
# Generate a random number between 0 and 1:
x = rn.random()
# Generate a random number between 0 and 1:
y = rn.random()
# If (x, y) lies inside the circle, increase counter I:
if x**2 + y**2 <= 1:
I += 1
# Calculate and display the final result:
result = 4*I/N
print(’Approximate value of pi =’, result)
Sample results for various values of N are shown in the following table:
Notice that a very large number of random points is needed to obtain the value of π accurate at least to two decimal digits – this is characteristic for Monte Carlo methods.
Table of Contents
- 1. Introduction
- 2. Using Python as a Scientific Calculator
- 3. Drawing, Plotting, and Data Visualization with Matplotlib
- 4. Working with Text Strings
- 5. Variables and Types
- 6. Boolean Values, Functions, Expressions, and Variables
- 7. Lists, Tuples, Dictionaries, and Sets
- 8. Functions
- 9. The ’For’ Loop
- 10. Conditions
- 11. The ’While’ Loop
- 12. Exceptions
- 13. File Operations
- 14. Object-Oriented Programming I – Introduction
- 15. Object-Oriented Programming II – Class Inheritance
- 16. Object-Oriented Programming III – Advanced Aspects
- 17. Recursion
- 18. Decorators
- 19. Selected Advanced Topics