0 characters
9. Conditional if-elif-else statement in Python
Summary- The conditional
if
construction allows you to make program branches, thus you can control the progress of the program.- The keywords
if
,elif
andelse
are used in the conditional construction.- The keyword
if
is always specified first in the conditional construction.- Using
elif
, you can add other conditions that will be fulfilled after checking theif
condition.- The
else
block will be executed only if all the conditions inif
andelif
are false.- In Python, the code block is indented.
- True values in Python include any non-zero number, any non-empty string, and any non-empty object.
- The
in
operator allows you to determine the presence of an element in a sequence, for example, in a row or list.- Boolean operators
and
,or
andnot
return one of the operands, not a Boolean value.- Other instructions, including conditional ones, can be used inside conditional instructions.
In the previous lesson we learned how to format strings using the format()
method and f-strings. Now let's take a little break from working with types in order to better understand the need for a theory from next lesson.
Conditional if
construction
The conditional if
construction allows you to branch the program when a given condition is met. We touched it a little bit in the introductory lesson, and now let's look at it in more detail.
In this construction, the keyword if
is mandatory, in turn, the keywords elif
and else
are used if necessary. Important points:
- the keyword
if
is always specified first in the conditional construction; - after the keyword
if
there should be a condition and, if it is true (returnsTrue
), then the code in the block is executed; - using
elif
, you can add other conditions that will be fulfilled after checking theif
condition; elif
cannot exist withoutif
. The keywordelif
is specified only afterif
;- the
else
block will be executed only if all the conditions inif
andelif
are false (returnFalse
).
It is easier to consider an example:
a = 2
if (a == 2):
print("Two")
elif (a == 3):
print("Three")
else:
print("Another number")
As you have already understood, the program will output "Two", since the condition a == 2
is true (i.e. returns True
):
print(a == 2) # => True
Please note that the condition written in parentheses is followed by a "colon" sign, and the subsequent block of code is indented (tabulated). In Python, the code block is indented, otherwise the interpreter will consider it an error. For example:
# Правильно
if (a == 2):
print("Digit")
print("Two")
# Неправильно
if (a == 2):
print("Digit")
print("Two")
In the following example, the word "Digit" will be output only if a
is equal to 2
, and the word "Two" will be output regardless of the condition:
if (a == 2):
print("Digit")
print("Two")
Now let's figure out what is true in Python (True
) and what is false (False
).
The true values in Python include:
- any number is not equal to zero;
- any non-empty string;
- any non-empty object.
False values in Python include:
- zero (
0
); None
;- an empty line;
- an empty object.
For example, to find out an empty list or not, you can do this:
l = [1, 2, 3, 4, 5]
if (l):
print("Not empty")
else:
print("Empty")
Comparison operators have already been considered earlier. In order not to come back to you, here they are:
a == b
– checks if both operands are equal and returns true if so;a != b
– checks if both operands are equal and returns true if they are different;a > b
– returns true if the left operand (a) is greater than the right operand (b);a < b
– returns true if the left operand (a) is less than the right operand (b);a >=b
– returns true if the left operand (a) is greater than or equal to the right operand (b);a <=b
– returns true if the left operand (a) is less than or equal to the right operand (b).
Note that equality is checked using the double equal symbol. One "equals" character indicates an assignment operation. Another example with comparison operators:
if a > b:
print("a is greater than b")
elif a < b:
print("b is greater than a")
else:
print("a and b are equal")
By the way, the parentheses that were used in the conditions of the first example are optional, i.e. you can write the condition without parentheses.
The in
operator
Python has a convenient in
operator that allows you to determine the presence of an element in a sequence, for example, in a row or list:
'a' in 'abcdef' # => True
'Hello' in 'Hello, World!' # => True
1 in [1, 2, 3, 4, 5] # => True
and
, or
, not
operators
Boolean operators and
, or
and not
they do not return a boolean value, they will always return one of the operands, for example:
'a' and 'b' # => b
'a' and 'b' and 'c' # => c
When using the and
operator, the values are checked from left to right. We have already found out what is true and what is false. The characters a
, b
, c
refer to "any non-empty string". So, if all the elements are true, then the last element will be returned.
0 and 'b' # => 0
'a' and [] and 'c' # => []
There are false objects in the example above. In this case, the and
operator will return the first false object. In the case of the or
operator, the first true object will be returned and, only if all are false, the last false object will be returned.
I'll say it again: the and
and or
operators they do not return True
and False
, but one of the operands (although, in a conditional construction, this will mean the same thing).
The not
operator inverts the logical value of the operand. If the operand is false, True
will be returned, otherwise False
. The not
operator in Python returns True
or `False', not an operand:
not 0 and 'b' # => b
'a' and not []# => True
Nested conditional instructions
In Python, as in other programming languages, other instructions can be used inside conditional instructions, including the same conditional ones. That is, you can put one instruction into another indefinitely, within reason, of course. The main thing is not to forget about the mandatory margins:
if (a > 0): # 0 spaces
if (a < 3): # 4 spaces or one tab
if (a == 2): # 8 spaces or two tabs
... # 12 spaces or three tabs
In this lesson, we learned how to use the conditional statement if-elif-else
in Python, remembered the list of true and false objects, and got acquainted with the operators in
, and
, or
and not
, which can significantly simplify writing code.
In the next lesson we will learn how to determine which type of data an object belongs to and convert from one to another.
Test task
Subscribe to our Telegram channel!
News, useful material,
programming and InfoSec