3.1 — Order of Expression Evaluation, Comparing Values, Conditional Execution

Debugging in Thonny to understand expression evaluation

In Thonny, we can use debugging features to understand how expressions are evaluated:

  • To show variables and their values, go to menu “View -> Variables”
  • First, run program in debug mode by clicking the “Debug current script” button (located next to the “Run current script” button and looks like a bug)
  • Then, we have two options:
    • Run the program line-by-line using “Step over” button next to the “Debug” button
    • Run program going inside each expression using “Step into” button (located next to “Step over” button)

Try the following examples in Thonny and use debug:

1x = 7
2
3# Increment value of variable x by 1
4x = x + 1
5
6#
7y = x * x + 2 * (x + 1) + max(x + 1, 5)
8
9# Calling print() with 4 arguments
10print("x =", x, "y =", y)

1x1 = 1.5
2y1 = 2
3
4print("Given points:", "(", x1, ",", y1, ")")
5
6point1 = "(" + str(x1) + ", " + str(y1) + ")"
7print("Given points:", point1)

Boolean Values

Python has two values True and False of type bool, which are useful for expressing and storing yes/no or true/false kind of data.

1>>> True
2True
3>>> False
4False
5>>> type(True)
6<class 'bool'>
7>>> type(False)
8<class 'bool'>

Comparison Operators

comparison operators, also known as relational operators, are used to compare two values, such as numbers or string.
The result of such comparison is always a bool value i.e. True or False.

1# are these numbers equal?
2>>> 10 == 10
3True
4>>> 10 == 20
5False
1>>> x = 5
2>>> y = 10
3>>> x == y
4False
5>>> x < y
6True
7>>> x > y
8False

1# A variable can store the result of a boolean expression
2# (just like we did for arithmetic expressions)
3>>> x = 3
4>>> is_positive = (x > 0)
5>>> is_positive
6True
7
8>>> x = 5
9>>> y = 5
10>>> is_equal = (x == y)
11>>> is_equal
12True

Boolean Expressions

A boolean expression is an expression that evaluates to either True or False. Examples above show how boolean expressions are created using comparison operators.

  • Common error is using = (single equals sign) instead of == (double equals sign)
  • = is the assignment operator, used to create variable and assign it a value
  • == is a comparison operator used to check for equality between two values

List of comparison operators

  • x == yTrue if x is equal to y, otherwise False
  • x != yTrue if x is not equal to y, otherwise False
  • x < yTrue if x is less than y, otherwise False
  • x > yTrue if x is greater than y, otherwise False
  • x <= yTrue if x is less than or equal to y, otherwise False
  • x >= yTrue if x is greater than or equal to y, otherwise False

Order of operations

All comparison operators (e.g. ==, !=, etc.) have same priority and are evaluated from left to right.

All arithmetic and string operators have higher priority than comparison operators.

1>>> x = 5
2# + operator will be evaluated before ==
3>>> x + 1 == 6
4True

Write a program that takes an integer as input from the user and displays on your screen whether it is true or false that such integer is even.

Output
Enter a number: 5
5 is an even number: False
Output
Enter a number: 8
8 is an even number: True
1num = int(input("Enter a number: "))
2# Write code below

1num = int(input("Enter a number: "))
2
3# a number is even if remainder is 0 when it is divided by 2
4is_even = (num % 2 == 0)
5
6print(num, "is an even number:", is_even)
7
8# without using extra variable:
9# print(num, "is an even number:", num % 2 == 0)

Comparing strings

Comparison operators work for strings as well.
The comparison is done alphabetically i.e. following a dictionary order

1>>> "cat" == "cat"
2True
3>>> "cat" == "dog"
4False
5>>> "cat" != "Cat"
6True
1# "c" appears before "d" alphabetically
2>>> "cat" < "dog"
3True
4
5# A-Z appear before a-z alphabetically
6>>> "cat" < "Dog"
7False

1# Objects of different types are always not equal
2>>> "cat" == 123
3False
4
5# inequality is not allowed
6# between a number and str
7>>> "cat" < 123
8TypeError: '<' not supported between instances of 'str' and 'int'
9
10# All of the above examples work the same when using variables
11>>> s1 = "cat"
12>>> s2 = "dog"
13>>> s1 == s2
14False

Equality and floating point numbers

Consider following example:

1>>> x = 1.1 + 2.2
2>>> x == 3.3 # why is this False?
3False
  • As we saw earlier, a floating-point number is stored with 64-bit finite precision.
  • This means that a number may not be stored as precisely as we would like.

Correct way to check if two float values are equal

We should check if they are “close enough”.

1>>> epsilon = 0.000001 # define how close two numbers need to be
2
3>>> x = 1.1 + 2.2
4>>> x
53.3000000000000003
6
7# Check if x and 3.3 are within epsilon distance
8>>> abs(x - 3.3) < epsilon
9True

The epsilon value depends on the application and how much error we are willing tolerate.

Logical Operators

Logical operators are useful to combine multiple conditions.

Logical operators take boolean expressions as operands and produce a result of type bool when evaluated.

Python has 3 boolean operators:

  • not — a unary operator
  • and — binary operator
  • or — binary operator

Suppose x is a variable of type bool:

xnot x
FalseTrue
TrueFalse

not x evaluates to the opposite value of x.

Suppose x and y are variables of type bool:

xyx and y
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
xyx or y
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

x and y evaluates to True if and only if both x and y are True.

x or y evaluates to False if and only if both x and y are False.

Order of operations

In order of higher to lower priority: not, and, or

As usual, we can use parentheses in order to change the priority.

What does b and not a or b evaluate to if a = False and b = True ?

  • b and not a or b
  • True and not False or True
  • True and True or True
  • True or True
  • True

What does a and not (a or b) evaluate to if a = True and b = False ?

  • a and not (a or b)
  • True and not (True or False)
  • True and not True
  • True and False
  • False

Updated operator precedence table

OperatorAssociativity
() (parentheses)-
**Right
Unary --
*, /, //, %Left
Binary +, -Left
==, !=, <, >, <=, >=Left
not-
andLeft
orLeft
= (assignment)Right

You don’t need to memorize all this, use parenthesis when in doubt!

Try these examples in Thonny

Change the value of x and see results of boolean expressions.

1x = 30
2# Is an even number greater than 20?
3print(x % 2 == 0 and x > 20)
4
5x = 10
6# Is an even number or a multiple of 5 greater than 20?
7print(x % 2 == 0 or x % 5 == 0 and x > 20)
8
9# Is a multiple of 2 or 5, greater than 20?
10print((x % 2 == 0 or x % 5 == 0) and x > 20)

Try it!

Write a program that takes 3 integers x,y,zx, y, z as inputs and prints out True if yy is an even number between xx and zz, False otherwise. Assume all 3 numbers will be different.

1# Retrieve inputs from the user
2x = int(input("Enter the x: "))
3y = int(input("Enter the y: "))
4z = int(input("Enter the z: "))
5
6# Write code below

1# Retrieve inputs from the user
2x = int(input("Enter the x: "))
3y = int(input("Enter the y: "))
4z = int(input("Enter the z: "))
5
6# check if y is even
7is_even = y % 2 == 0
8
9# check if y is between x and z
10is_between = (x < y and y < z) or (z < y and y < x)
11
12print(is_even and is_between)

Flow of execution

  • Flow of execution refers to order in which statements (lines of code) in our program are executed.
  • So far in our programs, each line was executed unconditionally.
  • For most programs, it is not enough as we need to make choices or run code repeatedly.

We need to control the flow of execution in our programs.

Control flow

The control flow of a program determines:

  • Which parts of the code should always be executed
  • Which parts should be executed only under certain conditions
  • Which parts should be executed repeatedly

All of these can be achieved using control flow statements:

  • if statement for conditional execution
  • for and while loops for repeated execution

if statement — to execute or not to execute

if condition : code block

  • condition must be a boolean expression
  • code block is one of more Python statements
  • code block is executed only if the condition is True, otherwise it is skipped.

Notice space before code block. It is called indentation.

Indentation is required to tell Python that the code belongs inside if statement.

Typically, 4 spaces are used for indentation. We can use tab key to indent.

Try the following examples with different values for variables.

1x = 10
2if x > 0:
3 print(x, "is positive")
1num = -5.2
2
3absolute_num = num
4
5if num < 0:
6 absolute_num = -num
7
8print("Absolute value of", num, "is", absolute_num)

1x = 1000
2y = 123
3
4min_value = x
5
6if y < min_value:
7 min_value = y
8
9print("Minimum of", x, "and", y, "is", min_value)

if statement with else part

if statements can have else part to make a choice between two code blocks.

if condition : code block1 else : code block2

  • When condition is True, code block1 is executed
  • Otherwise (condition is False) and code block2 is executed
  • The code blocks are also called branches of the if-statement.

1x = 10 # change this to -5 and run
2
3if x > 0:
4 print("x is positive.")
5else:
6 print("x is not positive.")

Write a program that takes an integer as input from the user and displays whether the number is even or odd.

Output
Please enter a number: 5
The number 5 is odd
Output
Please enter a number: 8
The number 8 is even

1num = int(input("Please enter a number: "))
2
3# a number is even if remainder is zero when divided by 2
4if num % 2 == 0:
5 print("The number", num, "is even")
6else:
7 print("The number", num, "is odd")