Introduction to Python Programming. Section 6. Boolean Values, Functions, Expressions, and Variables

6 Boolean Values, Functions, Expressions, and Variables

6.1 Objectives

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.

6.2 Why learn about Booleans?

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.

6.3 Boolean values

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:

  flag = True

<class ’bool’>


  flag2 = False

<class ’bool’>

6.4 Boolean functions

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 otherwise:

  var = ’Hello!’
  test = isinstance(var, str)


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 values:

  import numpy as np
  a = [1, 2, 3]
  b = [1, 2, 4]
  result = np.equal(a, b)

[True, True, False]

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:

  def divisible(a, b):
      return a % b == 0
  result = divisible(121, 11)


6.5 Comparison operators for numbers

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:

  print(1 < 2.3)


Of course one can compare numerical variables as well:

  a = 5
  b = 10
  print(a > b)


The modulo operator % can be used to check whether a number is even,

  a = 22
  print(a % 2 == 0)



Boolean expressions involving numbers or numerical variables mostly contain the following comparison operators:

 Symbol   Meaning

>  greater than
>=  greater than or equal to
<=  less than or equal to
<  less than
==  equal to
!=  not equal to
<>  not equal to (same as !=)

6.6 Comparison operator == vs. assignment operator =

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:

  a = 1
  print(a == 2)


The assignment operator = is used to assign a value to a variable, and it does not return anything:

  print(a = 1)

  on line 1:
  TypeError: ’a’ is an invalid keyword argument for this function

6.7 Comparison operators for text strings

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 you:

  a = ’Hello!’
  b = ’hello!’
  print(a == b)


But the result of this comparison may be a bit surprising:

  a = ’Monday’
  b = ’Friday’
  print(a > b)


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.

6.8 Storing results of Boolean expressions in variables

The results of Boolean expressions are Boolean values True or False. They can be stored in variables which then automatically become Boolean variables. For example:

  a = 1
  result = a < 1


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:

  a = 13
  result = 169 % a == 0


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.

6.9 Example: Checking if there exists a triangle with edge lengths a, b, c

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:


Fig. 51: Triangle with edges of length a, b, c.

Clearly, all three values must be greater than zero:

A = a > 0 and b > 0 and c > 0

Furthermore, the three values also need to satisfy the triangle inequality:

B = a + b > c or b + c > a or a + c > b
Hence the numbers a, b, c form an admissible input if the following Boolean expression C is True:
C = A and B
Here is the corresponding Boolean function checktriangle(a, b, c) which returns True if there exists a triangle with edge lenghts a, b, c and False otherwise:

  def checktriangle(a, b, c):
      Check if there exists a triangle with edge lengths a, b, c.
      A = a > 0 and b > 0 and c > 0
      B = a + b > c or b + c > a or a + c > b
      return A and B
  # Main program:
  a = 3
  b = 4
  c = 5
  result = checktriangle(a, b, c)


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.

6.10 Logical and and its truth table

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:

  a = 1
  v1 = a > 0
  v2 = a < 5
  print(v1 and v2)


Here both v1 and v2 are True, so v1 and v2 is True. Let’s look at one additional example:

  a = 6
  v1 = a > 0
  v2 = a < 5
  print(v1 and v2)


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 

 True    True    True  

 True   False   False 

 False   True   False 

 False  False   False 

6.11 Logical or and its truth table

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:

  a = 10
  v1 = a < 0
  v2 = a > 5
  print(v1 or v2)


Here v1 is False and v2 is True, therefore v1 or v2 is True. Another example:

  a = 3
  v1 = a < 0
  v2 = a > 5
  print(v1 and v2)


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 

 True    True    True  

 True   False   True 

 False   True   True 

 False  False   False 

6.12 Negation not

Negation not is a logical operation that changes the value of a Boolean expression from True to False and vice versa:

  a = 3
  v1 = a < 0
  print(not v1)


Here v1 is False, therefore not v1 is True.

The truth table of the not operator is very simple:

A  not A 

 True    False  

 False   True 

6.13 Booleans in conditions and the while loop

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:

  if True:
      print(’Condition is automatically satisfied.’)
      print(’Condition is not satisfied.’)

Condition is 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 program:

  if DEBUG:
      print(’Debug mode: x =’, x)

Debug mode: x = 4

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:

  while True:
      a = input(’Enter your age:’)
      if a.isdigit() and int(a) > 0:
          print(’Thank you.’)
          print(’Please enter your age (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:

  n = 100
  if n % 10 == 0:
      print(’Number’, n, ’is divisible by 10.’)
      print(’Number’, n, ’is not divisible by 10.’)

Number 100 is divisible by 10.

6.14 Example: Monte Carlo calculation of π

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):


Fig. 52: Monte Carlo calculation of π.

The red part is a quarter-circle whose area is C = πr24 = π∕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

 I    C    π
---≈  --=  --
N     A    4
and therefore

π ≈ ---
In summary, all we need to do is generate N random points (x,y) in the unit square, count the number I of points which lie in the quarter circle,

  2   2
x  + y  ≤ 1,
and then 4I∕N will give us an approximate value of π.

The program and sample results

We will use the Random library that you know from Subsection 2.16:

  # Import the Random library:
  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:

N  result 

 100    3.48  

 1000   3.272 

 10000    3.1576  

 100000   3.13764 

 1000000   3.14113 

 10000000  3.14253 

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

Created on August 6, 2018 in Python I,   Python II.
Add Comment
0 Comment(s)

Your Comment

By posting your comment, you agree to the privacy policy and terms of service.