© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_4

4. Flow Control

Kevin Wilson1  
(1)
London, UK
 

Flow control is controlling the order in which statements or function calls of a program are executed.

There are three control structures: sequence, selection, and iteration.

Python has various control structures such as while loops, for loops, and if statements, which are used to determine which section of code is executed according to certain conditions.

Sequence

A computer program is a set of step-by-step instructions that are carried out in sequence to achieve a task or solve a problem. The sequence can contain any number of instructions, but no instruction can be skipped in the sequence. Figure 4-1 illustrates this.

A workflow diagram of the step-by-step sequence of a computer program depicts executing the first line to the third line of code.

Figure 4-1

A computer program’s step-by-step sequence

The interpreter will follow and execute each line of code in sequence until the end of the program.

Let’s have a look at a program. Open adder.py. This program has four statements.

Two windows have a series of codes. The Python 3.8.1 Shell window carried out the instructions in sequence.

Once you execute the program, the instructions are carried out in sequence .

Let’s try another example. Open inchestocm.py.

Two windows have a series of codes. The Python 3.8.1 Shell window carried out the instructions of length in centimeters and centimeters to inches.

Selection

In most computer programs, there are certain points where a decision must be made. This decision is based on a condition, and that condition can be either true or false.

if... else

If statements are used if a decision is to be made. If the condition is true, then the if statement will execute the first block of code; if the condition is false, the if statement will execute the “else” block of code if included.

A workflow diagram depicts if the stated condition is false, execute the else block of code and if the stated condition is true, execute the first block of code.

Figure 4-2

An if… else statement

So, for example:
if num >= 0: #condition
    print("Positive or Zero") #first block
else:
    print("Negative number") #else block

Let’s have a look at a program. Open selection.py. Here, we can see a very simple if statement to determine whether a test score is a pass or fail. The pass mark is 70, so we need an if statement to return a pass message if the value entered is greater than 70. Remember that we also need to cast the variable “mark” as an integer (int).

If you enter a value greater than 70, the Python interpreter will execute the first block of the “if statement .”

Two windows have a series of codes. The highlighted second line code is the result, You've passed the statement since the value entered is greater than 70.

If you enter a value below 70, the Python interpreter will execute the “else block” of the “if statement .”

Two windows have a series of codes. The third line code, You've failed, try again statement is highlighted since the value entered is lower than 70.

elif

Use the elif statement if multiple decisions are to be made. Each decision (or condition) will have a set of instructions to be executed.

A workflow diagram of Elif statement conditions depicts each decision or condition whether true or false, has a set of instructions to be executed.

Figure 4-3

An elif statement

So, for example:
if condition:    #if condition
    [statements]    #first block of code
elif condition:  #first elif statement
    [statements]    #second block of code
elif condition:  #second elif statement
    [statements]    #third block of code
else:
    [statements] #else block of code

Let’s have a look at a program. Open multiselection.py .

Two windows have a series of codes. The code is for executing different grades depending on the value entered.

If we analyze the elif statement, we can see how it works. For the first condition, any number entered above 70 will execute the first block .

A process flow of the elif statement first condition. if the number entered above 70 the first block will be executed.

Any number between 60 and 69, the interpreter will execute the second block.

A flow model of the second condition of the elif statement. The second block will be executed if the number entered is between 60 and 69.

Similarly for the other conditions, 50–59 and 40–49.

A model of the third condition of the elif statement. The third block will be executed if the number entered above falls between 50 and 59 and 40 and 49.

If any condition is not met by the above “elif” statements, the interpreter will execute the “else” block at the end .

An illustration of an elif statement that did not meet any of the conditions. In the end, the else block will be executed.

Iteration (Loops)

A loop is a set of statements that are repeated until a specific condition is met. We will look at two types of loops: the for loop and the while loop.

For Loop

A for loop executes a set of statements for each item in a sequence such as a list or string or a range. It allows a code block to be repeated a specific number of times.

A workflow diagram depicts that each item in the sequence has to execute a block of code in the loop.

Figure 4-4

A for loop

This particular loop will print out each name in the list on a new line:
list = ['john', 'lucy', 'kate', 'mike']
for val in list:
     print (val) #block of code in loop

Let’s have a look at a program. Open forloop.py. The for loop contains a loop condition. In this example, the loop will execute for each item in the fruitlist [sequence].

Two windows have a series of codes. The code in the Python 3.8.1 Shell window is creating the sequence for the list of fruits in for loop dot p y window.

The “item” variable in the “for loop” statement is a pointer or counter to the current value or item in the sequence .

A line of code for creating a for loop statement has the item banana highlighted with an arrow in the fruit list.

For each of these “items,” the interpreter will execute everything inside the loop, in this example the “print” statement:
print (item, end=' ')

The interpreter will test the condition in the for loop again, and if it is true, the interpreter will execute everything inside the loop again. In each iteration of the loop, the counter moves to the next value or item.

A line of code for creating a for loop statement has the item orange highlighted with an arrow in the fruit list.

At the end of the sequence, the loop condition becomes false, so the loop terminates .

Let’s look at another example. Open forloop2.py.

Two windows have a series of codes. The Python 3.8.1 shell window executes the for loop statement from 1 to 9.

When you run through the program, you can see what it’s doing.

A workflow diagram of the counter in range, 1 to 10. If yes, print, counter, end equals single quote, backslash n, single quote, and if no, End loop.

While Loop

A while loop executes a set of statements while a certain condition is true. It allows the set of statements in the code block to be repeated an unknown number of times and will continue to repeat while the condition is true.

A workflow diagram for a while loop depicts a true or false condition. If true, execute a block of code in the loop.

Figure 4-5

A while loop

This particular loop will keep prompting the user for a string until the user enters the word “fire”:
userInput = ''
while userInput != 'fire':
     userInput = input ('Enter passcode: ')

Let’s have a look at a program. Open whileloop.py. The while loop contains a loop condition .

Two windows have a series of codes. The Python 3.8.1 shell window contains a loop condition of the current temperature in Celsius.

When you run through the program, you can see what it’s doing:

A workflow diagram of a while loop statement is a temperature lower than 26. If yes, print, temp, temp equals temp plus 1, and if no, then end loop.

Break and Continue

The break statement breaks out of a loop. In this example, the loop breaks when the counter is equal to 5.
while (counter < 10):
    if counter == 5:
        break
    counter = counter + 1
The continue statement jumps back to the top of the loop without executing the rest of the code after the continue keyword. In this example, the loop restarts when “number” is even.
myList = [1, 2, 3, 4, 5, 6, 7, 8]
for number in myList:
    if number % 2 == 0: #if number even
        continue
    print(number)

Lab Exercises

Take a look at the following exercises and use what you’ve learned to solve the problems.
  1. 1.

    Write a program to print the numbers 1–10 to the screen.

     
  2. 2.

    Write a program to print a list of names to the screen.

     
  3. 3.

    Write a program to calculate and print the squares of the numbers from 1 to 10. Use tabs to display them in a table.

     
  4. 4.

    Write a program that accepts a number from the user until a negative number is entered.

     
  5. 5.

    Write a program that accepts an integer and prints the specified range it belongs to:

     

Range 1: 0 to 10

Range 2: 11 to 20

Range 3: 21 to 30

Range 4: 31 to 40

Summary

  • Flow control is controlling the order in which statements or function calls of a program are executed.

  • Sequence is the set of step-by-step instructions carried out in order to achieve a task or solve a problem.

  • Selection is the point at which a decision is to be made. For this, we use IF statements.

  • Iteration is where we need to repeat several lines of code multiple times. For this, we use WHILE and FOR loops.

  • Use FOR loop if you know how many times you’re going to execute the loop, such as processing a range or list.

  • If you need to repeat code until a condition is to be met, use a WHILE loop.

  • The break statement breaks out of a loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.54.63