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 = 723# Increment value of variable x by 14x = x + 156#7y = x * x + 2 * (x + 1) + max(x + 1, 5)89# Calling print() with 4 arguments10print("x =", x, "y =", y)
1x1 = 1.52y1 = 234print("Given points:", "(", x1, ",", y1, ")")56point1 = "(" + 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>>> True2True3>>> False4False5>>> 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 == 103True4>>> 10 == 205False
1>>> x = 52>>> y = 103>>> x == y4False5>>> x < y6True7>>> x > y8False
1# A variable can store the result of a boolean expression2# (just like we did for arithmetic expressions)3>>> x = 34>>> is_positive = (x > 0)5>>> is_positive6True78>>> x = 59>>> y = 510>>> is_equal = (x == y)11>>> is_equal12True
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 == y — True if x is equal to y, otherwise False
- x != y — True if x is not equal to y, otherwise False
- x < y — True if x is less than y, otherwise False
- x > y — True if x is greater than y, otherwise False
- x <= y — True if x is less than or equal to y, otherwise False
- x >= y — True 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 = 52# + operator will be evaluated before ==3>>> x + 1 == 64True
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.
Enter a number: 5 5 is an even number: False
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: "))23# a number is even if remainder is 0 when it is divided by 24is_even = (num % 2 == 0)56print(num, "is an even number:", is_even)78# 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"2True3>>> "cat" == "dog"4False5>>> "cat" != "Cat"6True
1# "c" appears before "d" alphabetically2>>> "cat" < "dog"3True45# A-Z appear before a-z alphabetically6>>> "cat" < "Dog"7False
1# Objects of different types are always not equal2>>> "cat" == 1233False45# inequality is not allowed6# between a number and str7>>> "cat" < 1238TypeError: '<' not supported between instances of 'str' and 'int'910# All of the above examples work the same when using variables11>>> s1 = "cat"12>>> s2 = "dog"13>>> s1 == s214False
Equality and floating point numbers
Consider following example:
1>>> x = 1.1 + 2.22>>> 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 be23>>> x = 1.1 + 2.24>>> x53.300000000000000367# Check if x and 3.3 are within epsilon distance8>>> abs(x - 3.3) < epsilon9True
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:
x | not x |
---|---|
False | True |
True | False |
not x evaluates to the opposite value of x.
Suppose x and y are variables of type bool:
x | y | x and y |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
x | y | x or y |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
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
Operator | Associativity |
---|---|
() (parentheses) | - |
** | Right |
Unary - | - |
*, /, //, % | Left |
Binary +, - | Left |
==, !=, <, >, <=, >= | Left |
not | - |
and | Left |
or | Left |
= (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 = 302# Is an even number greater than 20?3print(x % 2 == 0 and x > 20)45x = 106# Is an even number or a multiple of 5 greater than 20?7print(x % 2 == 0 or x % 5 == 0 and x > 20)89# 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,z as inputs and prints out True if y is an even number between x and z, False otherwise. Assume all 3 numbers will be different.
1# Retrieve inputs from the user2x = int(input("Enter the x: "))3y = int(input("Enter the y: "))4z = int(input("Enter the z: "))56# Write code below
1# Retrieve inputs from the user2x = int(input("Enter the x: "))3y = int(input("Enter the y: "))4z = int(input("Enter the z: "))56# check if y is even7is_even = y % 2 == 089# check if y is between x and z10is_between = (x < y and y < z) or (z < y and y < x)1112print(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 expressioncode block
is one of more Python statementscode block
is executed only if the condition is True, otherwise it is skipped.
Notice space before code block. It is called indentation.
Typically, 4 spaces are used for indentation. We can use tab key to indent.
Try the following examples with different values for variables.
1x = 102if x > 0:3 print(x, "is positive")
1num = -5.223absolute_num = num45if num < 0:6 absolute_num = -num78print("Absolute value of", num, "is", absolute_num)
1x = 10002y = 12334min_value = x56if y < min_value:7 min_value = y89print("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) andcode block2
is executed - The code blocks are also called branches of the if-statement.
1x = 10 # change this to -5 and run23if 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.
Please enter a number: 5 The number 5 is odd
Please enter a number: 8 The number 8 is even
1num = int(input("Please enter a number: "))23# a number is even if remainder is zero when divided by 24if num % 2 == 0:5 print("The number", num, "is even")6else:7 print("The number", num, "is odd")