Lesson 09: Control commands in Python

Normally, the execution flow of a program has a fixed process in which the code is read and executed line by line, from top to bottom; Control commands are the ability to control or change this constant current. Using these commands, you can set a condition for the execution of a block that if this condition is not met at the time of execution, the execution of the block will be canceled or conditions can be created for the execution of a block to be selected from several specific blocks. The execution of a block can be repeated several times. This lesson is devoted to examining Python control commands in two sections, “Selection” and “Repetition”.

✔ Level: Introductory

Headlines

Lesson 09: Control commands in Python

Selection Repetition

Selection

Using the selection command, you can determine whether a command block will be executed or not, and which of the two or more command blocks will be selected and executed according to the program conditions at runtime. Python offers only one selection structure that can be implemented in three forms: “single-choice”, “two-choice” and “multi-choice”; This structure is called the if statement and will be discussed below.

If statement

1. Simple structure (single selection)

This structure is a composite command in which a “condition” is checked, and the body will execute only if this condition is met; Otherwise, the interpreter waives the command (s) of the body and goes to the first command after this structure. This structure is implemented using the if keyword and a similar pattern below:

if condition :
 StatementBlock

A condition is an expression that can be evaluated as one of the Boolean values (True or False); Here, if the condition is set to True, the body part of the if statement is executed. Note the sample codes below:

>>> a = 5
>>> b = 3
>>> if a > b:
... print("a is greater than b")
...
a is greater than b
>>>
>>> if a == b:
... print("a is equal to b")
...
>>>

In the example of the above code, the condition is evaluated as False and the execution of the body is refused; So no text is printed in the output.

>>> if a > b and a >= 0:
... print("a is positive and greater than b")
...
a is positive and greater than b
>>>

As can be seen in the example code above, logical operators (not, or, and) can be used to check that several conditions are present (or not) at the same time.

We know that: The number one and all the opposite numbers of zero in Python are equal to the Boolean value True and the number zero, empty objects such as “” or [] are valued as False:

>>> if 1:
... print("Condition is True")
...
Condition is True
>>>
>>> if []:
... print("Condition is True")
...
>>>
>>> a = False
>>> if not a:
... print("Condition is True")
...
Condition is True
>>>

The if structure can also be nested. In this case, the body of the if statement contains one or more other if statements, which of course can also contain other if statements in their body:

>>> d = {'name': 'Jhon', 'job': 'programmer', 'age': 40}
>>> if d['age'] >= 40:
... if d['job'] == 'programmer':
... print(d['name'])
...
Jhon
>>>

2. Structure with else (two choices)

Using the else keyword, you can specify a block to execute when the condition is not met – when the if condition is valued equal to the Boolean False value. else is a separate section that has its own header and body; This header must have no conditions:

>>> a = False
>>> if a:
... print("Condition is True")
... else:
... print("Condition is False")
...
Condition is False
>>>
>>> a = 7
>>> if a in [1, 2, 3]:
... print("a is in list")
... else:
... print("a is not in list")
...
a is not in list
>>>
>>> d = {'name': 'Bob', 'job': 'designer', 'age': 45}
>>> if d['age'] >= 40:
... if d['job'] == 'programmer':
... print(d['name'])
... else:
... print(d['name'], d['job']) # Will be executed
... else:
... if d['age'] >= 35:
... print(d['name'], 'Between 35 and 40 years old')
... else:
... print(d['name'], 'Less than 35 years old')
...
Bob designer
>>>

3. Structure with elif (multiple choice)

The if statement can be extended to create more sections with different conditions; In this case, the condition of the if part is checked first, and if it is not evaluated as True, the condition of the first part of the elif is checked. If it is not equal to True again, the condition of the next elif part will be checked and so on; Finally, if none of the conditions (if and elif) are equal to True, then the body of the else section (if any) is executed. The pattern of this structure is as follows:

if condition_1:
 statements
elif condition_2:
 statements
elif condition_3:
 statements
else:
 statements
  • Each elif is a separate part that has its own head and body.
  • The number of elif sections is optional and there is no limit.
  • The elif section cannot be placed before if or after else.
  • In this structure, the existence of the else section is optional.

In this structure, the sections are examined from top to bottom, and with the True evaluation of the condition of each section, the body related to it is executed and the review of other sections is omitted. Note the example code below:

>>> percent = 60
>>> if percent == 100:
... print('100 %')
... elif percent >= 75:
... print('75-100 %')
... elif percent >= 50:
... print('50-75 %')
... elif percent >= 25:
... print('25-50 %')
... else:
... print('less than 25 %')
...
50-75 %
>>>

If we want to implement the above code example using nested ifs, it will look like this:

>>> percent = 60
>>> if percent == 100:
... print('100 %')
... else:
... if percent >= 75:
... print('75-100 %')
... else:
... if percent >= 50:
... print('50-75 %')
... else:
... if percent >= 25:
... print('25-50 %')
... else:
... print('less than 25 %')
...
50-75 %
>>>

If you want to check all the required conditions, you can use several if statements in a row:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File: Documents/script.py
# Python 3.x
import sys
# Get script argument and convert it to an integer
percent = int(sys.argv[1])
if percent == 100:
 print('100 %')
if percent >= 75:
 print('75-100 %')
if percent >= 50:
 print('50-75 %')
if percent >= 25:
 print('25-50 %')
if percent < 25:
 print('less than 25 %')
user> cd Documents/
user> python script.py 60
50-75 %
25-50 %

Switch / case command

If you have a history of programming with other languages such as C and Java, you must be familiar with the switch command; This command is not implemented in Python.

The switch command receives a value and then compares it with the values of each case within its structure, respectively; If this value is equal to one of the cases, it executes the commands associated with that case and ignores the other cases. Also, if the value received does not match any of the cases, it executes the commands related to the default section (if any). The following are examples of this command in Java:

int success;
char grade = 'B';
switch (grade) {
 case 'A':
 System.out.println("Excellent grade");
 success = 1;
 break;
 case 'B':
 System.out.println("Very good grade");
 success = 1;
 break;
 case 'C':
 System.out.println("Good grade");
 success = 1;
 break;
 case 'D':
 case 'E':
 case 'F':
 System.out.println("Low grade");
 success = 0;
 break;
 default:
 System.out.println("Invalid grade");
 success = -1;
 break;
}

If / elif / else can be used to implement such a structure in Python:

grade = 'B'
if grade == 'A':
 print('Excellent grade')
 success = 1
elif grade == 'B':
 print('Very good grade')
 success = 1
elif grade in ('D', 'E', 'F'):
 print('Low grade')
 success = 0
else:
 print('Invalid grade')
 success = -1

Repetition

Sometimes we need to run a block several times in a row. The repetitive structure is called a loop; In the following, we will examine the structure of the two loops presented in the Python language.

While command

This compound command is a loop that repeats a condition in its header and executes body commands if the condition is set to True; The interpreter returns to the header after the execution of the body and checks the condition that if the condition is still valid, the body commands are executed again. Normally the repetition process will continue until the header condition is set to True. The pattern of this command is as follows:

while condition :
 statements

The condition must always be controlled from within the body so that at a certain stage it is evaluated equal to the value of False; Otherwise an infinite loop is created that the interpreter can never get out of. For example, the execution of the following command is never completed by the Python interpreter, and the operating system must be used to complete it:

>>> while 1:
... print('Press Ctrl+C to stop!')
...
Press Ctrl+C to stop!
Press Ctrl+C to stop!
Press Ctrl+C to stop!
[..]

But in the example of the code below, the value of the variable a decreases from inside the control body and each unit decreases; Therefore, the loop continues only as long as the condition is not violated:

>>> a = 5
>>> while a > 0:
... print(a)
... a -= 1 # a = a - 1
...
5
4
3
2
1
>>>

In the above code example, it would be better to use only the variable a itself as a loop condition instead of a> 0; Because each time the execution is reduced by one unit, and when it reaches the value of zero, it is automatically evaluated by the Python interpreter to the value of False and the execution of the loop body is stopped.

As another example, the Factorial number 10 can be calculated as follows:

>>> a = 10
>>> n = 1
>>> while a >= 1:
... n = n * a
... a -= 1
...
>>> print(n)
3628800

Order of Continu

This command is ignored at any point in the body section, subsequent commands are ignored, and the execution stream jumps to the beginning of the loop, the header section. For example, we want to display even integers less than 10 on the output. In the example of the code below for odd numbers, the continue statement prevents the execution and display of them and jumps the execution stream to the beginning of the loop:

>>> n = 10
>>> while n:
... n -= 1
... if n % 2 != 0:
... continue
... print(n)
...
8
6
4
2
0
>>>

Of course, the above example can also be done without continue:

>>> n = 10
>>> while n:
... n -= 1
... if n % 2 == 0:
... print(n)

Command of break

This command is ignored at any point in the body section, subsequent commands are ignored, and the execution stream leaves the loop. In the example of the code below, with each execution of the body, a unit is added to the counter, and when its value is equal to 4, regardless of the condition, the execution of the loop is stopped:

>>> counter = 0
>>> while counter < 100:
... if counter == 4:
... break
... print(counter)
... counter += 1
...
0
1
2
3
>>>

In while we can also use the else section; In this way, if the loop ends naturally – and not by the break statement – then the body else is executed.

The sample code below checks whether the number n is a “prime number“; These numbers are greater than one and are not divisible by any number except themselves and the number one. Therefore, if a number less than n (except one) is found that is divisible by it (that is, the remainder divided by it is zero), the first n is proved not to be n, and the loop is stopped by the break statement:

>>> n = 23
>>> i = 2
>>> while i < n:
... if n % i == 0:
... print(n, "is not a prime number")
... break
... i += 1
... else:
... print(n, "is a prime number")
...
23 is a prime number
>>>

Command for

This composite command is a loop that repeats the execution of body commands based on the number of members of a sequence object or, more generally, an iterator object, which will be examined at the end. The pattern of this command is as follows:

for target in object:
 statements

Each for loop is repeated exactly the number of members of the object; Each time a member of the object sequence (or repeater) is assigned to the target variable while maintaining the order of the members, the body is executed once; This process continues until the end of the object members navigation. The target variable can be used inside the body, which in the first instance of the loop will refer to the first member and with subsequent performances to the next members of the object. Note the sample codes below:

>>> for item in [1, 2, 3]:
... print(item)
...
1
2
3
>>>
>>> for char in 'python':
... print(char)
...
p
y
t
h
o
n
>>>
>>> L = [(1, 2), (3,4), (5, 6)]
>>> for a, b in L:
... print(a, b)
...
1 2
3 4
5 6
>>>

In the example code above, since each member of its sequence is a two-member sequence, two variables are used to refer to the navigation object.

>>> L = [(1, 2), (3,4), (5, 6)]
>>> for both in L:
... a, b = both
... print(a, b)
...
1 2
3 4
5 6
>>>

In the example code above, the variable both refers to a tuple object each time it is repeated.

>>> a, *b, c = (1, 2, 3, 4)
>>> a, b, c
(1, [2, 3], 4)
>>> for a, *b, c in [(1, 2, 3, 4), (5, 6, 7, 8)]:
... print(a, b, c)
...
1 [2, 3] 4
5 [6, 7] 8
>>>
>>> d = {'name': 'Jhon', 'job': 'designer', 'age': 40}
>>> for key in d:
... print(key)
...
name
job
age
>>>

Normally for a dictionary object, its keys are scrolled.

>>> d = {'name': 'Jhon', 'job': 'designer', 'age': 40}
>>> d.items()
dict_items([('name', 'Jhon'), ('job', 'designer'),
('age', 40)])
>>> for key, value in d.items():
... print(key, value)
...
name Jhon
job designer
age 40
>>>

Attention

The for loop is usually used when the number of iterations is known and the while loop when the number of iterations is unknown.

Like the while loop, the continue and break commands can also be used here. The for loop can also contain the else section.

Let’s rewrite the example of recognizing the first number in the while loop using the for loop:

>>> n = 23
>>> for i in range(2, n):
... if n % i == 0:
... print(n, "is not a prime number")
... break
... else:
... print(n, "is a prime number")
...
23 is a prime number
>>>

Function range (stop):

This function [Python documents 3x] returns an object of range type; This object is an immutable sequence that is usually used to navigate the for loop. By converting the range object to a list type, we will see that this object is an ordered sequence of numbers from zero to the stop argument (and not itself); The stop argument must be a positive integer:

>>> r = range(10) # Python 3.x
>>> type(r)
<class 'range'>
>>> r
range(10)
>>> print(r)
range(10)
>>> list(r)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tuple(r)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> import sys
>>> sys.getsizeof(r)
48

This function can also be called as two arguments range (start, stop))) where the first argument determines the starting number of the sequence and can also be a negative number:

>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(-2, 10))
[-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this case, a third argument can be used to determine the step or distance between numbers:

>>> list(range(2, 10, 2))
[2, 4, 6, 8]
>>> list(range(2, 10, 3))
[2, 5, 8]
>>> list(range(2, 10, 4))
[2, 6]
  • All three arguments must be of the correct type.
  • To specify a negative stop argument, the step argument must also be specified negatively:
>>> list(range(2, -10, -1))
[2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(2, -10, -2))
[2, 0, -2, -4, -6, -8]
>>> list(range(-2, -10, -1))
[-2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(-2, -10, -2))
[-2, -4, -6, -8]

There are two versions of this function in the 2x versions of Python: the range function [2x Python documents] and the xrange function [2x Python documents].

The output of the range function is a list object:

>>> r = range(10) # Python 2.x
>>> type(r)
<type 'list'>
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import sys
>>> sys.getsizeof(r)
152

But the output of the xrange function is an object of type xrange:

>>> r = xrange(10) # Python 2.x
>>> type(r)
<type 'xrange'>
>>> r
xrange(10)
>>> list(r)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import sys
>>> sys.getsizeof(r)
40

The output of the xrange function is simpler and more efficient than the output of the range function, so it is usually recommended to use the xrange function in the for loop; This is why the range function has been removed in the 3x Python versions, leaving only the xrange function implemented with the range name and type.

  • How to use and the number of arguments to both functions is the same as the 3x version discussed earlier.

A few other simple examples:

>>> L = ['a', 'b', 'c', 'd']
>>> for i in range(len(L)):
... print(L[i])
...
a
b
c
d
>>>
>>> s = 'pythonprogramminglanguage'
>>> for c in s[9:13]:
... print(c)
...
g
r
a
m
>>>
>>> reven = range(0, 10, 2)
>>> list(reven)
[0, 2, 4, 6, 8]
>>> rodd = range(1, 10, 2)
>>> list(rodd)
[1, 3, 5, 7, 9]
>>> list(zip(reven, rodd))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>> L = []
>>> for a, b in zip(reven, rodd):
... L.append(a*b)
...
>>> L
[0, 6, 20, 42, 72]

The results of the for loop can be placed directly in a list object; For example, consider the following command:

>>> L = []
>>> for x in range(5):
... L.append(x**2)
...
>>> L
[0, 1, 4, 9, 16]

Which can be easily rewritten below:

>>> [x ** 2 for x in range(5)]
[0, 1, 4, 9, 16]

And for other examples, look at the sample code below:

>>> y = 7
>>> [y * x for x in range(10)]
[0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
>>> L = [(1, 2), (3, 4), (5, 6)]
>>> [a + b for a, b in L]
[3, 7, 11]
>>> [a * b for a, b in zip(range(0, 10, 2), range(1, 10, 2))]
[0, 6, 20, 42, 72]
>>> [(a, b) for a, b in zip(range(0, 10, 2), range(1, 10, 2))]
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

Python composite commands can be used inside each other’s bodies, which is also true for for and while commands. Both of these commands can be used inside each other’s body or nested as needed:

>>> for i in range(1, 5):
... for j in range(0, i):
... print(i)
...
1
2
2
3
3
3
4
4
4
4
>>>

Note the example code above; Each time the first loop is repeated, all of its body instructions, which include another loop, are executed. The variable i inside the inner loop is also used. In the first execution of the outer loop, the value of i is set to 1, in which case the execution of the inner loop is repeated only once (1 == ((len (range (0, 1)) and a value of 1 is displayed in the output. دوم The second time i is equal to the number 2, and as a result the inner loop is repeated twice, as a result of which two values of 2 are printed on the output, and this process continues until the end of the outer loop is repeated.

The print function (or command) goes to the next line by default after executing and printing the value. [The next lesson will look at how to change this behavior]

If you are already familiar with languages like C or Java; To better understand the structure of the Python for loop, consider the example code below, which is in Java:

int[][] array = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
for ( int row = 0; row < array.length; row++ )
{
 for ( int column = 0; column < array[ row ].length;
column++ )
 System.out.printf( "%d ", array[ row ][ column ] );
 System.out.println();
}
// Paul Deitel, Harvey Deitel "Java: How to Program"
(9th Edition) page 270
1 2
3
4 5 6

Which we can implement in Python below:

>>> array = ((1, 2), (3,), (4, 5, 6))
>>> for row in range(0, len(array)):
... for column in range(0, len(array[row])):
... print("%d " % array[row][column])
... print()

Function enumerate (iterable):

In addition to the range () function in for loops we can also use the enumerate () function [Python documents]. This function takes a sequence or iterator object as an argument and returns an enumerate object:

>>> L = ['a', 'b', 'c']
>>> e = enumerate(L)
>>> type(e)
<class 'enumerate'>
>>> e
<enumerate object at 0x7fc76a6b92d0>
>>> print(e)
<enumerate object at 0x7fc76a6b92d0>
>>> import sys
>>> sys.getsizeof(e)
72

By converting this object to a list object, it is observed that this object has stored its input argument members in pairs with their position index (index, value):

>>> list(e)
[(0, 'a'), (1, 'b'), (2, 'c')]

Using this function is very useful when considering a non-numeric sequence or checking the loop sequence index:

>>> s = 'python'
>>> for i, v in enumerate(s):
... print('%s) %s' % (i, v * 7))
...
0) ppppppp
1) yyyyyyy
2) ttttttt
3) hhhhhhh
4) ooooooo
5) nnnnnnn
>>>
>>> s = 'python'
>>> [v * i for i, v in enumerate(s)]
['', 'y', 'tt', 'hhh', 'oooo', 'nnnnn']

This function also has an optional argument called start, which can be set to the initial number of indexes; The default value of this argument is zero:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Duplicate object

In this section, we are going to get acquainted with the concept of iterator in Python. For this purpose, it is better to first know the concept of iterable.

All sequence types are iterable; In fact, objects with the ability to access a member at any one time are called iterable. Most of the ready-made objects we know in Python are iterable; Types of string objects, lists, tuples, dictionaries, ranges, zip (or xrange) or a file object, and any object of the class that you define yourself with special methods (__ iter__) or (__ getitem__) are iterable.

The iterator object is created using the ready iter () function [Python Documents]; This function takes an iterable object as an argument and returns it as an iterator object:

>>> L = [1, 2, 3, 4, 5]
>>> type(L)
<class 'list'>
>>> itr = iter(L)
>>> type(itr)
<class 'list_iterator'>
>>> t = (1, 2, 3, 4, 5)
>>> type(t)
<class 'tuple'>
>>> itr = iter(t)
>>> type(itr)
<class 'tuple_iterator'>
>>> s = 'python'
>>> type(s)
<class 'str'>
>>> itr = iter(s)
>>> type(itr)
<class 'str_iterator'>
>>> d = {'name': 'Bob', 'age': 40}
>>> type(d)
<class 'dict'>
>>> itr = iter(d)
>>> type(itr)
<class 'dict_keyiterator'>

An iterator object has the ability to navigate its members one by one using the __ next__ () (or (next)) method in Python 2x); This method returns the first time calling the first member of the object and the next time calling the next members in order:

>>> L = [1, 2, 3, 4, 5]
>>> itr = iter(L)
>>> # Python 3.x
>>> itr.__next__()
1
>>> itr.__next__()
2
>>> itr.__next__()
3
>>> # Python 2.x
>>> itr.next()
1
>>> itr.next()
2
>>> itr.next()
3

By repeatedly calling this method and reaching the end of the scroll; When there is no longer a member to return, an error – of course it is fair to say an Exception – is reported as StopIteration:

>>> itr.__next__()
4
>>> itr.__next__()
5
>>> itr.__next__()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
StopIteration

This is exactly what is done in the for command. When you use a sequence to scroll through this command; for behind the scenes turns it into an iterator and then starts scrolling the members one by one. Whenever StopIteration occurs, it notices the end of the sequence and ends the loop repetition.

In the future you will see in the Exceptions lesson in Python that you can implement a while loop like a for loop by creating an iterator and using the try / except command [which you will learn in the same lesson].

Using the itertools module, you can create infinite or non-stop iterators. For example, the cycle function inside this module creates an iterator object that does not stop at the end of the scroll and returns to the beginning of the object and returns the first member:

>>> import itertools
>>> L = [1, 2, 3, 4, 5]
>>> itr = itertools.cycle(L)
>>> type(itr)
<class 'itertools.cycle'>
>>> itr.__next__()
1
>>> itr.__next__()
2
>>> itr.__next__()
3
>>> itr.__next__()
4
>>> itr.__next__()
5
>>> itr.__next__()
1
>>> itr.__next__()
2

This module contains many useful functions that you can read more about in the Python documentation page.

😊 I hope it was useful

The best HTML Articles are availalbe on our website in many categories: HTML, CSS, jQuery and free online tools. Browse our articles to learn web content composing!

Leave a Reply

Your email address will not be published. Required fields are marked *