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)
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)
You can also ask a comparison question using the >
(greater than) operator.
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).
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).
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?
true_or_not
expression represents the truth (i.e., its value is not equal to zero), the indented statement(s) will be executed;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
if
keyword;True
(when its value is non-zero) and False
(when it is equal to zero);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.)
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:
perform_if_condition_true
statement is executed, and the conditional statement comes to an end;perform_if_condition_false
statement is executed, and the conditional statement comes to an end.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:
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;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:
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;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.
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
:
Operator | Description | Example |
---|---|---|
== | returns if operands’ values are equal, and False otherwise | x == y # False x == z # True |
!= | 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:
if
statement, e.g.:x = 10
if x == 10: # condition
print(“x is equal to 10”) # Executed if the condition is True.
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.
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.
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”)
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”)
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—