Python — Control flow statements 

Python — Control flow statements 

vvrubel

Track content


If statement

§1. Simple if statement

There are situations when your program needs to execute some piece of the code only if a particular condition is true. Such a piece of the code should be placed within the body of an if statement. The pattern is the same as in the English language: first comes the keyword if , then a condition, and then a list of expressions to execute. The condition is always a Boolean expression, that is, its value equals either True or False. Here is one example of how the code with a conditional expression should look like:

biscuits = 17
if biscuits >= 5:
    print("It's time for tea!")

Note that the condition ends with a colon and a new line starts with an indentation. Usually, 4 spaces are used to designate each level of indentation. A piece of code in which all lines are on the same level of indentation is called a block of code. In Python, only indentation is used to separate different blocks of code, hence, only indentation shows which lines of code are supposed to be executed when the if statement is satisfied, and which ones should be executed independently of the if statement. Check out the following example:

if biscuits >= 5:
    print("It's time for tea!")
    print("What tea do you prefer?")
print("What about some chocolate?")

In this example, the line "It's time for tea!", as well as "What tea do you prefer?", will be printed only if there are 5 or more biscuits. The line "What about some chocolate?" will be printed regardless of the number of biscuits.

An if statement is executed only if its condition holds (the Boolean value is True), otherwise, it's skipped.

Boolean values basically make it clear whether a piece of code needs to be executed or not. Since comparisons result in bool, it's always a good idea to use them as a condition.

There is one pitfall, though. You should not confuse the comparison operator for equality == with the assignment operator =. Only the former provides for a proper condition. Try to avoid this common mistake in your code.

§2. Nested if statement

Sometimes a condition happens to be too complicated for a simple if statement. In this case, you can use so-called nested if statements. The more if statements are nested, the more complex your code gets, which is usually not a good thing. However, this doesn't mean that you need to avoid nested if statements at all costs. Let's take a look at the code below:

rainbow = "red, orange, yellow, green, blue, indigo, violet"
warm_colors = "red, yellow, orange"
my_color = "orange"

if my_color in rainbow:
    print("Wow, your color is in the rainbow!")
    if my_color in warm_colors:
        print("Oh, by the way, it's a warm color.")

The example above illustrates a nested if statement. If the variable my_color is a string that contains the name of a color from the rainbow, we enter the body of the first if statement. First, we print the message and then check if our color belongs to the warm colors. The membership operator in simply shows whether my_color is a substring of the respective string, rainbow or warm_colors. Just like arithmetic comparisons, it returns a boolean value.

Here is what we will see in our case:

Wow, your color is in the rainbow!
Oh, by the way, it's a warm color.

When it comes to nested if statements, proper indentation is crucial, so do not forget to indent each statement that starts with the if keyword.


Up!

Else statement

§1. Simple if-else

An if-else statement is another type of conditional expressions in Python. It differs from an if statement by the presence of the additional keyword else. The block of code that else contains executes when the condition of your if statement does not hold (the Boolean value is False). Since an else statement is an alternative for an if statement, only one block of code can be executed. Also, else doesn't require any condition:

if today == "holiday":
    print("Lucky you!")
else:
    print("Keep your chin up, then.")

Note that the 4-space indentation rule applies here too.

As you may soon find out, programmers do like all sorts of shortcuts. For conditional expressions there's a trick as well – you can write an if-else statement in one line. This is called a ternary operator and looks like this:

print("It’s a day now!" if sun else "It’s a night for sure!")

Or, more generally:

first_alternative if condition else second_alternative

It's a matter of convenience, but remember that the code you create should still be readable.

§2. Nested if-else

It should be mentioned, that if-else statements can be nested the same way as if statements. An additional conditional expression may appear after the if section as well as after the else section. Once again, don't forget to indent properly:

if x < 100:
    print('x < 100')
else:
    if x == 100:
        print('x = 100')
    else:
        print('x > 100')
    print('This will be printed only because x >= 100')

Now you are ready not only to set conditions but also to consider different alternatives. Congratulations!


Up!

Elif statement

Since you are familiar with basic conditional statements, such as if statement and if-else statement, it’s time for the more advanced elif statement.

Elif statement is used when we want to specify several conditions in our code. How does it differ from if-else statements? Well, it's simple. Here we add the elif keyword for our additional conditions. It is mostly used with both if and else operators and the basic syntax looks like this:

# basic elif syntax
if condition1:
    action1
elif condition2:
    action2
else:
    action3

The condition is followed by a colon, just like with the if-else statements, the desired action is placed within the elif body and don't forget about an indentation, i.e., 4 spaces at the beginning of a new line. Here we first check the condition1 in the if statement and if it holds (the value of the Boolean expression is True), action1 is performed. If it is False, we skip action1 and then check the condition2 in the elif statement. Again, if condition2 is True, action2 is performed, otherwise, we skip it and go to the else part of the code.

Let's take a look at the example below:

# elif example
price = 10000 # there should be some int value
if price > 5000:
    print("That's too expensive!")
elif price > 500:
    print("I can afford that!")
else:
    print("That's too cheap!")

To buy or not to buy? To answer the question we first check if the price is higher than 5000. If ‘price > 5000’ is True, we print that it’s too expensive and set off, looking for something cheaper. But what if the price was less than 5000? In this case, we check the next condition is ‘price > 500’, and again, if it is True, we print out that we can afford that, and if it is False, we go to the else block and print that it's too cheap. So “I can afford it!” will be printed if the price is less than 5000 but more than 500, and “That’s too cheap” if the price is lower than 500.

Elif statement differs from else in one key moment: it represents another specific option while else fits all cases that don't fall into the condition given in if statement. That's why sometimes you may encounter conditional statements without else:

pet = 'cat'  # or 'dog'?

# cats vs dogs conditional
if pet == 'cat':
    print('Oh, you are a cat person. Meow!')
elif pet == 'dog':
    print('Oh, you are a dog person. Woof!')

In this example, it's possible to add an else statement to slightly expand a perspective, but it's not necessary if we are only interested in dogs and cats.

§1. Why elif and not if?

The last example probably made you wonder: why did we use elif statement instead of just two if statements? Wouldn't two if statements be easier?

if pet == 'cat':
    print('Oh, you are a cat person. Meow!')
if pet == 'dog':
    print('Oh, you are a dog person. Woof!')

In this particular case, the result would be the same as with elif. But this wouldn't work as needed for the first example of this topic:

price = 6000
if price > 5000:
    print("That's too expensive!")
if price > 500:
    print("I can afford that!")
else:
    print("That's too cheap!")
# The output is 'That's too expensive!\nI can afford that!'

See? We got two contradicting messages instead of one that we originally intended to output. The difference between the above examples is that in the example with pets, the cases described by conditional statements are mutually exclusive, that is, there's no string that would be equal both to 'dog' and 'cat' at the same. In the other example, the cases aren't mutually exclusive, and there are values for price that can satisfy both conditions.

So, elif statement is a better alternative than two if statements when you want to show that only one of the conditions is supposed to be satisfied. A chain of if statements implies that the conditions stated in them are totally unrelated and can be satisfied independently of each other, like in the following example:

animal = 'unicorn'
if animal in 'crow, dog, frog, pony':
    print('This animal exists')
if animal in 'unicorn, pegasus, pony':
    print('This animal is a horse')

With this distinction in mind, you'll be able to make your code more clear and less error-prone. Now, let's get back to studying elif functionality.

§2. Multiple elifs and a decision tree

There can be as many elif statements as you need, so your conditions can be very detailed. No matter how many elif statements you have, the syntax is always the same. The only difference is that we add more elifs:

# multiple elifs syntax
if condition1:
    action1
elif condition2:
    action2
# here you can add as many elifs as you need
elif conditionN:
    actionN
else:
    actionN1

The code inside the else block is executed only if all conditions before it are False. See the following example:

# multiple elifs example
light = "red"  # there can be any other color
if light == "green":
    print("You can go!")
elif light == "yellow":
    print("Get ready!")
elif light == "red":
    print("Just wait.")
else:
    print("No such traffic light color, do whatever you want")

In this program, the message from the else block is printed for the light of any color except green, yellow and red for which we’ve written special messages.

Conditionals with multiple branches make a decision tree, in which a node is a Boolean expression and branches are marked with either True or False. The branch marked as True leads to the action that has to be executed, and the False branch leads to the next condition. The picture below shows such a decision tree of our example with traffic lights.


§2. Nested elif statements

Elif statements can also be nested, just like if-else statements. We can rewrite our example of traffic lights with nested conditionals:

# nested elifs example
traffic_lights = "green, yellow, red"
# a string with one color
light = "purple"  # variable for color name
if light in traffic_lights:
    if light == "green":
        print("You can go!")
    elif light == "yellow":
        print("Get ready!")
    else:
        # if the lights are red
        print("Just wait.")
else:
    print("No such traffic light color, do whatever you want")

Since you have mastered the topic of conditionals, from now on you can make your program do what you want when you want it!


Up!

While loop

Sometimes one iteration (=execution) of a statement is not enough to get the result you need. That is why Python offers a special statement that will execute a block of code several times. Meet the loop command and one of the universal loops — the while loop.

People generally don't choose Python to write fast code. The main advantages of Python are readability and simplicity. As the while loop requires the introduction of extra variables, iteration takes up more time. Thus, the while loop is quite slow and not that popular. It resembles a conditional operator: using the while loop, we can execute a set of statements as long as the condition is true.

The condition itself (2) is written before the body of the loop (some call it the conditional code) and is checked before the body is executed. If the condition is true (3a), the iterations continue. If the condition is false (3b), the loop execution is terminated and the program control moves further to the next operation.

§1. Visualization

If we visualize the while loop, it’ll look like this:

number = 0
while number < 5:
    print(number)
    number += 1
print('Now, the number is equal to 5')

The variable number plays here the role of a counter – a variable that changes its value after each iteration. In this case, the iterations continue until the number is equal to 5 (note that the program outputs the value of the number before increasing it). When the value of a counter reaches 5, the program control moves to the next operation and prints the message. Here you can see the output of this code:

0
1
2
3
4
Now, the number is equal to 5

§2. The infinite loop

If you delete a part of the conditional code where you increase the value of a counter, you will bump into the infinite loop. What does it mean? Since you don’t increase your variable, a condition never becomes false and can work forever. Usually, it is a logical fallacy, and you'll have to stop the loop using special statements or finishing the loop manually.

Sometimes the infinite loop can be useful, e.g. in querying a client when the loop works continuously to provide the constant exchange of information with a user. You can implement it by writing True as a condition after the while header.

while True:
    ...

Now you are familiar with the while loop and its usage. Don’t forget about the role of a counter, otherwise, you’ll have to deal with the infinite loop. After you’ve written the code, try to "run" it as if you were a Python program. That’ll help you understand how the loop works.

Programming is all about simplification, so the code should be readable, short, and clear. Don’t forget about comments and syntax. In the beginning, it may seem that the while loop is not that easy to implement, but after a couple of times, you’ll see that it’s a very useful tool.


Up!

For loop

§1. What is iteration?

Computers are known for their ability to do things which people consider to be boring and energy-consuming. For example, repeating identical tasks without any errors is one of these things. In Python, the process of repetitive execution of the same block of code is called an iteration.

There are two types of iteration:

  • Definite iteration, where the number of repetitions is stated in advance.
  • Indefinite iteration, where the code block executes as long as the condition stated in advance is true.

After the first iteration, the program comes back to the beginning of the code’s body and repeats it, making the so-called loop. The most used one is the for loop, named after the for operator that provides the code’s execution.

§2. For loop syntax

Here is the scheme of the loop:

for variable in iterable:
    statement

where statement is a block of operations executed for each item in iterable, an object used in iteration (e.g. string or list). Variable takes the value of the next iterable after each iteration.

Now try to guess which output we'll get if we execute the following piece of code:

oceans = ['Atlantic', 'Pacific', 'Indian', 'Southern', 'Arctic']
for ocean in oceans:
    print(ocean)

During each iteration the program will take the items from the list and execute the statements with them, so the output will be:

Atlantic
Pacific
Indian
Southern
Arctic

Even strings are iterable, so you can spell the word, for example:

for char in 'magic':
    print(char)

Like this:

m
a
g
i
c

§3. Range function

The range() function is used to specify the number of iterations. It returns a sequence of numbers from 0 (by default) and ends at a specified number. Be careful: the last number won’t be in the output.

Let's look at the example below:

for i in range(5):
    print(i)

What we'll get is this:

0
1
2
3
4

You can change the starting value if you’re not satisfied with 0, moreover, you can configure the increment (step) value by adding a third parameter:

for i in range(5, 45, 10):
    print(i)

According to the parameters included, we’ve asked to print the numbers from 5 to 45 with an increment value of 10. Be careful again, the last value is not included in the output:

5
15
25
35

If you're not going to use the counter variable in your loop, you can show it by replacing its name with an underscore symbol:

for _ in range(100):
    do_smth()

In the example above, we don't need the counter variable in any way, we simply use the loop to repeat do_smth() function a given amount of times.

§4. Input data processing

You can also use the input() function that helps a user to pass a value to some variable and work with it. Thus, you can get the same output as with the previous piece of code:

word = input()
for char in word:
    print(char)

Oh, look, you can write a piece of code with a practical purpose:

times = int(input('How many times should I say "Hello"?'))
for i in range(times):
    print('Hello!')

You can, therefore, ask a user to specify the number of iterations to be performed.

§5. Nested loop

In Python, it is easy to put one loop inside another one – a nested loop. The type of inner and outer loops doesn't matter, the first to execute is the outer loop, then the inner one executes:

names = ['Rose', 'Daniel']
surnames = ['Miller']
for name in names:
    for surname in surnames:
         print(name, surname)

The output is shown below:

Rose Miller
Daniel Miller

In this example, we use the two for loops to create fictional people's names. Obviously, you can deal with iterable objects of different sizes without too much fuss.

§6. To sum up

All in all, for loops are an efficient way to automatize some repetitive actions. You can add variables and operations to make a nested loop. Moreover, you can control the number of iterations with the help of the range() function. Be careful with the syntax: an extra indent or lack of colon can cause a mistake!


Up!

Loop control statements

§1. Modifying loops

Loop control statements are nested inside loops and designed to change their typical behavior. In this topic, we'll find out how they work and what they are used for.

§2. How to break

The break statement is used to terminate a loop of any type (i. e. for and while loops). It may be said that break "jumps out" of the loop where it was placed. Let’s examine a tiny example:

pets = ['dog', 'cat', 'parrot']
for pet in pets:
    print(pet)
    if pet == 'cat':
        break

We wanted to stop the loop before it iterated for the last time. For that purpose, we introduced a condition when the loop should be stopped. The output is as follows:

dog
cat

Be careful where you put print(). If you put it at the loop’s end, the output will return only the first value – ‘dog’. This happens because break exits from the loop immediately.

Often enough, break is used to stop endless while loops like this one:

count = 0
while True:
    print("I am Infinite Loop")
    count += 1
    if count == 13:
        break

§3. How to continue

The continue operator is commonly used, too. You can stop the iteration if your condition is true and return to the beginning of the loop (that is, jump to the loop's top and continue execution with the next value). Look at the following example:

pets = ['dog', 'cat', 'parrot']
for pet in pets:
    if pet == 'dog':
        continue
    print(pet)

The output will contain all values except the first one ('dog') since it fulfills the condition:

cat
parrot

Thus, the loop just skips one value and goes on running.

One nuance is worth mentioning: the continue operator should be used moderately. Sometimes you can shorten the code by simply using an if statement with the reversed condition:

pets = ['dog', 'cat', 'parrot']
for pet in pets:
    if pet != 'dog':
        print(pet)

In this case, the output will remain the same:

cat
parrot

§4. Loop else clause

If the loop didn’t encounter the break statement, an else clause can be used to specify a block of code to be executed after the loop.

pets = ['dog', 'cat', 'parrot']
for pet in pets:
    print(pet)
else:
    print('We need a turtle!')

So after the loop body, the else statement will execute:

dog
cat
parrot
We need a turtle!

Importantly, loop else runs if and only if the loop is exited normally (without hitting break). Also, it is run when the loop is never executed (e. g. the condition of the while loop is false right from the start). Consider an example:

pancakes = 2
while pancakes > 0:
    print("I'm the happiest human being in the world!")
    pancakes -= 1
    if pancakes == 0:
        print("Now I have no pancakes!")
        break
else:
    print("No pancakes...")

When we run the code for the first time we'll get this output:

I'm the happiest human being in the world!
I'm the happiest human being in the world!
Now I have no pancakes!

Execution of the code snippet for the second time (when the condition is not met, for pancakes = 0) will end up with another message:

No pancakes...

§5. In conclusion

To sum up, loop control statements represent a useful tool to alter the way a loop works. You can introduce extra conditions using breakcontinue and else operators. In addition, they allow you to print a message after the successful code execution, skip a beforehand selected set of values, or even terminate an endless loop. Use them wisely and they'll work wonders.


Up!


Report Page