Conditionals

1. The comparison (otherwise known as relational) operators are used to compare values. The table below illustrates how the comparison operators work, assuming that x = 0, y = 1, and z = 0:

Operator Description Example
== returns True if operands’ values are equal, and False otherwise
!= returns True if operands’ values are not equal, and False otherwise
x != y # True
x != z # False
> True if the left operand’s value is greater than the right operand’s value, and False otherwise
x > y # False
y > z # True
< True if the left operand’s value is less than the right operand’s value, and False otherwise
x < y # True
y < z # False
True if the left operand’s value is greater than or equal to the right operand’s value, and False otherwise
x >= y # False
x >= z # True
y >= z # True
True if the left operand’s value is less than or equal to the right operand’s value, and False otherwise
x <= y # True
x <= z # True
y <= z # False

2. When you want to execute some code only if a certain condition is met, you can use a conditional statement:

    • a single if statement, e.g.:
    • a series of if statements, e.g.:

Each if statement is tested separately.

    • an if-else statement, e.g.:
    • a series of if statements followed by an else, e.g.:

Each if is tested separately. The body of else is executed if the last if is False.

    • The if-elif-else statement, e.g.:

If the condition for if is False, the program checks the conditions of the subsequent elif blocks – the first elif block that is True is executed. If all the conditions are False, the else block will be executed.

    • Nested conditional statements, e.g.:

 

 

Exercise 1

What is the output of the following snippet?

 

False
True

 

Exercise 2

What is the output of the following snippet?

 

False
True

 

Exercise 3

What is the output of the following snippet?

 

True
False

 

Exercise 4

What is the output of the following snippet?

 

True
True
else

 

Exercise 5

What is the output of the following snippet?

 

four
five

 

Exercise 6

What is the output of the following snippet?

 

one
two

 

Ex. 7

What is the output of the following code snippet?

 

three

  • The program executes the else statement and outputs three to the console.
  • The if condition is False because the lowercase substring 'it' is not present in incipit.
  • The elif condition is also False, because the substring 'ht"'includes a quotation mark that is not part of the string contained in the incipit variable.

 

Ex. 8

What is the output of the following code snippet?


 

Correct answer

A

C