Python – branching structures (if else, if, ifelif statements)

The if statement (if) is used to set conditions (if so, then…), for example:

cat_say = ‘mew’

if cat_say = ‘mew’ of cat_say = ‘myavki’:

….print(‘Dear, cat! Here’s your food!’)

Important: when using if conditions, you need to write double equals and put a colon at the end of the expression to show the end of the condition; before the rest of the code related to the condition, and print is indented with a tab (or 4 spaces).

So the if condition is written like this:

if condition:

#continuation of the code

ifelse statement (if not, then). For example:

cat_say = ‘hi’

if cat_say == ‘mew’ or cat_say == ‘myavki’:

….print(“Here is your food!”)

else:

….print(“There is no food”)

Important: after the else there is a colon, on the next line, through the indentation, writes the code related to the case if the if condition is not met. This time we have replaced the value of the first variable with hi, which means if the condition is not met, then we will get the answer There is no food.

Each following condition in Python is written with extra indentation:

a=1

….if a<5:

……..if a<3:

…………print(a)

……..else:

…………print(“no”)

In this case, we will see the result 1, because the computer first checks the first condition 1<5, there is so; then – the second condition 1<3, that’s right, then print the value of variable a, that’s 1. If we set a=4, then the result will be no. If we set a=7, then nothing will happen, because for this option, we do not have actions.

It is important to remember about indentation, operators paired by the number of indentations correlate with each other.

elif statement (if not, check it before moving on to else)

cat_say = ‘hi’

if cat_say == ‘mew’ or cat_say == ‘myavki’:

….print(“Here is your food!”)

elif cat_say == ‘hi’:

….print(“Special food!”)

else:

….print(“There is no food”)

It is very important to understand the logic of if/elif/else statements:

if – this is the primary condition, if it turned out to be true, then the block ends here, if not, we proceed to check the following conditions; further in the code there can be as many elif one after another or under each other through indents – these are additional conditions, if at least one of them turns out to be true – this is where the block ends; else – tells the computer what to do if none of the previously described conditions are met.

That is, of all the specified if / elif / else conditions, only one can be true, because they should all be mutually exclusive. We will see the result of the condition that first turns out to be true.