etc are used to compare values and return a boolean. Logical operators like and, or, not are used to combine multiple boolean expressions. When comparing floating point numbers for equality, a small tolerance epsilon is used due to precision limitations."> etc are used to compare values and return a boolean. Logical operators like and, or, not are used to combine multiple boolean expressions. When comparing floating point numbers for equality, a small tolerance epsilon is used due to precision limitations.">
3.2 - Boolean Expressions, Comparison & Logical Operators
3.2 - Boolean Expressions, Comparison & Logical Operators
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
2 True
3 >>> False
4 False
5 >>> type(True)
6 <class 'bool'>
7 >>> type(False)
8 <class 'bool'>
Examples:
1 >>> 10 == 10 # are numbers equal?
2 True
3 >>> 10 == 20
4 False
5
6 >>> x = 5
7 >>> y = 10
8 >>> x == y
9 False
10 >>> x != y
11 True
12 >>> x < y
13 True
14 >>> x > y
15 False
16
17 # We can use variables to store results of boolean expression
18 # (just like we did for arithmetic expressions)
19 >>> x = 3
20 >>> is_positive = x > 0
21 >>> is_positive
22 True
23
24 >>> x = 5
25 >>> y = 5
26 >>> is_equal = x == y
27 >>> is_equal
28 True
Important
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
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 >>> x + 1 == 6
3 True
Try it!
Write a program that take an integer as input from the user and
displays on your screen whether it is true or false that such integer is
even.
Program should run as follows:
Output
Enter a number: 5
5 is an even number: False
Show answer
Comparing strings
or — binary operator
x not x
False True
True False
x y x and y x y x or y
Order of operations
and
or
Order of operations
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
1 x = 30
2 # Is an even number greater than 20?
3 print(x % 2 == 0 and x > 20)
4
5 x = 10
6 # Is an even number or a multiple of 5 greater than 20?
7 print(x % 2 == 0 or x % 5 == 0 and x > 20)
8
9 # Is a multiple of 2 or 5, greater than 20?
10 print((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.
Show answer