This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Comparison operators

Comparing variables

face Josiah Wang

Have I managed to get your brain juices running?

Now, let’s try using the comparison operators with variables. Here are more interesting questions for you to try.

1 2 3 4 5 6 7

Question 1

Assuming x=7, what is the value of the following boolean expression?

x >= 5 

True

Question 2

Assuming x=7 and y=3, what is the value of the following boolean expression?

x < y

False

Question 3

Assuming x=7, what is the value of the following boolean expression?

5 != x

True
Explanation:

Variables can be used on both left hand sides and right hand sides.

Question 4

Assuming x=7, what is the value of the following boolean expression?

x == x

True

Question 5

Assuming x=7, what is the value of the following boolean expression?

4 < x <= 7

True
Explanation:

Yes, you can chain boolean comparisons. Python parses this as 4 < x and x <= 7, and the value is True only if both 4 < x and x <= 7 are True.

Question 6

Assuming x=7 and y=3, what is the value of the following boolean expression?

x == 5 < y

False
Explanation:

Again, such chained expressions are allowed in Python. The value is True only if both x == 5 and 5 < 7 are True.

Question 7

Assuming x=7 and y=3, what is the value of the following boolean expression?

5+y > 3*x

False
Explanation:

The value of the first operand (5+3) is smaller than the second (3*7).