 ### Python Fundamentals and PCEP Certification Course

1- Introduction
2- Python Basic
3- Learning Python
4- Python Literals
5- Arithmetic operators
6- Function INPUT() and STRING operations
7- Comparison Operators and Conditions
8- Loops in Python
9- Logic and bit operators
10- Lists and Arrays in Python
11- Functions
12- Tuples, Dictionaries
13- Conclusion
14- Practice Exams

# L7.1 Comparison Operators and Conditional Execution of Code

## Comparison operators

### Equality: the equal to operator (==)

The `==` (equal to) operator compares the values of two operands. If they are equal, the result of the comparison is `True`. If they are not equal, the result of the comparison is `False`.

Write code below and see how it works.

var = 0 # Assigning 0 to var
print(var == 0)

Now, try below

var = 1 # Assigning 1 to var
print(var == 0)

### Inequality: the not equal to operator (!=)

The `!=` (not equal to) operator compares the values of two operands, too. Here is the difference: if they are equal, the result of the comparison is `False`. If they are not equal, the result of the comparison is `True`.

Write below code and see how it works.

var = 0 # Assigning 0 to var
print(var != 0)

Now, try below

var = 1 # Assigning 1 to var
print(var != 0)

### Comparison operators: greater than

You can also ask a comparison question using the `>` (greater than) operator.

### Comparison operators: greater than or equal to

The greater than operator has another special, non-strict variant, but it’s denoted differently than in classical arithmetic notation: `>=` (greater than or equal to).

### Comparison operators: less than or equal to

As you’ve probably already guessed, the operators used in this case are: the `<` (less than) operator and its non-strict sibling: `<=` (less than or equal to).

## Conditions and conditional execution

### Conditional execution

To make decisions in program, Python offers a special instruction. Due to its nature and its application, it’s called a conditional instruction (or conditional statement). For example, if output of code is above 100, display ‘over a hundred’ and if output of code is less than 100, display ‘under a hundred’. A conditional statement in python looks like this

if true_or_not:
do_this_if_true

How the above statement works?

• If the `true_or_not` expression represents the truth (i.e., its value is not equal to zero), the indented statement(s) will be executed;
• if the true_or_not expression does not represent the truth (i.e., its value is equal to zero), the indented statement(s) will be omitted (ignored), and the next executed instruction will be the one after the original indentation level.

Now, a real world example; if the weather is good, we’ll go for a walk then, we’ll have lunch. Look at the code below to reflect this real world example

if the_weather_is_good:
go_for_a_walk()
have_lunch()

Note following elements used in conditional statements

• the `if` keyword;
• one or more white spaces;
• an expression (a question or an answer) whose value will be interpreted solely in terms of `True` (when its value is non-zero) and `False` (when it is equal to zero);
• colon followed by a newline;
• an indented instruction or set of instructions (at least one instruction is absolutely required); the indentation may be achieved in two ways – by inserting a particular number of spaces (the recommendation is to use four spaces of indentation), or by using the tab character; note: if there is more than one instruction in the indented part, the indentation should be the same in all lines; even though it may look the same if you use tabs mixed with spaces, it’s important to make all indentations exactly the same – Python 3 does not allow mixing spaces and tabs for indentation.

### Conditional execution: the if statement

Take a look at following code

if sheep_counter >= 120:
make_a_bed()
take_a_shower()
sleep_and_dream()
feed_the_sheepdogs()

As you can see, making a bed, taking a shower and falling asleep and dreaming are all executed conditionally – when `sheep_counter` reaches the desired limit. Feeding the sheepdogs, however, is always done (i.e., the `feed_the_sheepdogs()` function is not indented and does not belong to the `if` block, which means it is always executed.)

### Conditional execution: the if-else statement

Now we know what we’ll do if the conditions are met, and we know what we’ll do if not everything goes our way. In other words, we have a “Plan B”. Python allows us to express such alternative plans. This is done with a second, slightly more complex form of the conditional statement, the if-else statement.

See the following code

if true_or_false_condition:
perform_if_condition_true
else:
perform_if_condition_false

The part of the code which begins with `else` says what to do if the condition specified for the `if` is not met (note the colon after the word). The if-else execution goes as follows:

• if the condition evaluates to True (its value is not equal to zero), the `perform_if_condition_true` statement is executed, and the conditional statement comes to an end;
• if the condition evaluates to False (it is equal to zero), the `perform_if_condition_false` statement is executed, and the conditional statement comes to an end.

### Nested if-else statements

Now let’s discuss two special cases of the conditional statement.

First special case: Consider the case where the instruction placed after the `if` is another `if`.

Read what we have planned for this Sunday. If the weather is fine, we’ll go for a walk. If we find a nice restaurant, we’ll have lunch there. Otherwise, we’ll eat a sandwich. If the weather is poor, we’ll go to the theater. If there are no tickets, we’ll go shopping in the nearest mall.

Let’s write the same in Python. Consider carefully the code here:

``````if the_weather_is_good:
if nice_restaurant_is_found:
have_lunch()
else:
eat_a_sandwich()
else:
if tickets_are_available:
go_to_the_theater()
else:
go_shopping()``````

Here are two important points on above code:

• this use of the `if` statement is known as nesting; remember that every `else` refers to the `if` which lies at the same indentation level; you need to know this to determine how the ifs and elses pair up;
• consider how the indentation improves readability, and makes the code easier to understand and trace.

Second special case: This introduces another new Python keyword: elif. A kind of shorter form of else if.

`elif` is used to check more than just one condition, and to stop when the first statement which is true is found.

``````if the_weather_is_good:
go_for_a_walk()
elif tickets_are_available:
go_to_the_theater()
elif table_is_available:
go_for_lunch()
else:
play_chess_at_home()
``````

Note: The way to assemble subsequent if-elif-else statements is sometimes called a cascade.

Some additional attention has to be paid in this case:

• you mustn’t use `else` without a preceding `if`;
• `else` is always the last branch of the cascade, regardless of whether you’ve used `elif` or not;
• `else` is an optional part of the cascade, and may be omitted;
• if there is an else branch in the cascade, only one of all the branches is executed;
• if there is no else branch, it’s possible that none of the available branches is executed.

Now, to understand conditional statement through practice, try writing following two example codes, run and analyze the output of each. Both solve the same problem i.e. how to find the largest number

Example Code 01: Finding the largest number with two numbers given as input

``````# Read two numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))

# Choose the larger number
if number1 > number2: larger_number = number1
else: larger_number = number2

# Print the result
print("The larger number is:", larger_number)

``````

Example code 02: Finding the largest number with three numbers given as input

``````# Read three numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))

# We temporarily assume that the first number
# is the largest one.
# We will verify this soon.
largest_number = number1

# We check if the second number is larger than current largest_number
# and update largest_number if needed.
if number2 > largest_number:
largest_number = number2

# We check if the third number is larger than current largest_number
# and update largest_number if needed.
if number3 > largest_number:
largest_number = number3

# Print the result
print("The largest number is:", largest_number)

``````

Now, how about scenario when your input consists of hundreds of numbers and you need to find the largest number? The above code won’t work. Fortunately, Python comes with a lot of built-in functions that will do the work for you. 🙂

For example, to find the largest number of all, you can use a Python built-in function called `max()`.

You can use it with multiple arguments. Analyze the code below. Try writing yourself and experiment with various numbers

``````# Read three numbers.
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))

# Check which one of the numbers is the greatest
# and pass it to the largest_number variable.

largest_number = max(number1, number2, number3)

# Print the result.
print("The largest number is:", largest_number)

``````

By the same fashion, you can use the `min()` function to return the lowest number.  Try it yourself.

## Exam notes

1. The comparison (or the so-called 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`:

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.:

x = 10

if x == 10: # condition
print(“x is equal to 10”) # Executed if the condition is True.

• a series of `if` statements, e.g.:

x = 10

if x > 5: # condition one
print(“x is greater than 5”) # Executed if condition one is True.

if x < 10: # condition two
print(“x is less than 10”) # Executed if condition two is True.

if x == 10: # condition three
print(“x is equal to 10”) # Executed if condition three is True.

• an `if-else` statement, e.g.:

x = 10

if x < 10: # Condition
print(“x is less than 10”) # Executed if the condition is True.

else:
print(“x is greater than or equal to 10”) # Executed if the condition is False.

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

x = 10

if x > 5: # True
print(“x > 5”)

if x > 8: # True
print(“x > 8”)

if x > 10: # False
print(“x > 10”)

else:
print(“else will be executed”)

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

x = 10

if x == 10: # True
print(“x == 10”)

if x > 15: # False
print(“x > 15”)

elif x > 10: # False
print(“x > 10”)

elif x > 5: # True
print(“x > 5”)

else:
print(“else will not be executed”)

• Nested conditional statements, e.g.:

x = 10

if x > 5: # True
if x == 6: # False
print(“nested: x == 6”)
elif x == 10: # True
print(“nested: x == 10”)
else:
print(“nested: else”)
else:
print(“else”)

—End of Topic—

2
0