Python programming language: loops

In the Python programming language (also “Python” or “Python”), there are several ways to loop some action. The main tools for implementing any kind of iteration in Python are while and for loops. The while loop is more universal than for, so it runs slower. However, this does not mean that he is better! The for loop is used much more often, because it can be used to implement the most complex tasks for creating multi-level and multi-conditional programs.

pytnon loops

Python: postcondition loop

Postcondition loops are while loops, which are the most versatile organizational constructs in a given programming environment. The while loop works on a “until” basis. This means the following: as long as some condition returns the true value, it will work! This construction is called a “cycle” because the functional control is cyclically repeated starting from the initial value. Exiting the while loop in Python will be implemented the moment the value becomes false. At this moment, the interpreter passes the execution of the program to the next functional-semantic segment, that is, a new line that is located after the block with the post-condition while.

python while loop

In the Python programming language, loops with the while postcondition have the following syntax:

1. While (condition):

2. expression

An expression can be either one instruction or several. A condition is always some true value or non-zero. A similar construction works as long as the given condition is true.

Using a while loop in Python using an example

python postcondition loop

Consider a while loop. Python structures its iterations quite interestingly:

a = 0
while a <7:
print ("A")
a = a + 1

We declared the variable "a" and set it to zero. Then we set the condition "while a <7", that is, while the variable "a" is less than the number "7", then our cycle will be executed until it becomes false.

And false (that is, it will exit the loop) it will become when the variable becomes greater than the number "7". For this to happen, each time it increases by 1, which we indicate in the line "a = a + 1".

If you run this design, then the letter "A" will be displayed 7 times in a column!

A
A
A
A
A
A
A

Python endless loop

How to make an endless while loop in Python? It is not at all difficult to guess, because the cycle works until it receives a false value, and if this value is simply not there? The answer to the question, probably, is already clear to everyone. In what cases is an infinite loop necessary to solve a problem? This example will be the implementation of such a program as the “clock”. Here, undoubtedly, it will be necessary to use an infinite loop that will permanently update and show time.

python infinite loop

An infinite loop is very often the mistake of beginning programmers who forget to add changes to the conditions of the cycle.

Let's take a look at the following snippet of Python code. The loops in this case are iterated endlessly (after the "#" symbol there is a comment):

number = 1 # declare the variable number and assign it a value of 1

while number <10: # create a postcondition in which number is less than 10

print 'Hello' # we fulfill the condition (print the message “Hello”)

Such a program should not be rushed to compile, because it will run endlessly. We set such conditions under which there will never be a false value: the condition "number <10" in this case is invariable and true, therefore iteration will be carried out continuously, displaying the Nth number of messages "Hello". In order to stop the eternal compilation process, you will need to press the key combination Ctrl + C in the shell.

Python: syntax. While and for loops

As mentioned above, in the Python programming language there are several ways to organize the repetition of a group of expressions. A for loop comes to the rescue, which is slightly different from its while counterpart, because its construction is somewhat more complicated than just a postcondition. We will not talk about the universality of this cycle, since it simply does not exist, but it can be noted that the for loop works much faster than while. The many ways to solve and the speed of this design outperform the cycle with the postcondition, so it is much more often used to perform many trivial tasks.

What are the challenges for the for loop? Undoubtedly, the same as while - iterate over any processes. In the programs executed on "Python", the for loop is widely used, which is capable of implementing a traversal of a given set of elements and performing various iterations over them in its body. The capabilities of this construction can be applied to the processing of strings or lists in the same way as any other iterable object.

Python for example

Suppose we have a list of numbers, and we need to increase each element (i.e., number) by three units. We can accomplish this task by looping, using the for loop.

Let's look at a small example where we will perform the appropriate actions for this (after the “#” symbol there is a comment):

spisok_chisel = [5, 15, 25, 35, 45, 55, 65, 75, 85, 95] # declared an array containing 10 digits

count = 0 # created a counter with a zero value

for elements in spisok_chisel: # iterate over the array and write it to elements

spisok_chisel [count] = elements + 3 # the number from the array is increased by three

count = count + 1 # go to the next number by index

The result of the above construction will be as follows:

spisok_chisel = [8, 18, 28, 38, 48, 58, 68, 78, 88, 98]

In our example, there is the variable count, which we need in order to note the changing values ​​in the array "spisok_chisel". The count variable records the index values ​​of each element in the array (each number in the list). The "elements" variable binds the resulting values ​​in the list. In the for loop, we observe how the processing of each numerical object in the list is implemented. Inside the loop, the sum of the current iterable element and triple is added to each numerical object with the “count” index. Then our “count” index is increased by one, and the program flow returns to the beginning of the declaration of the for construct. Thus, the loop will work until it processes each element in the array specified by the condition. If any element is missing, but specified by condition, the loop process will be completed. Let's pay attention to one more nuance: if you do not write the line “count = count + 1”, then, despite the fact that the objects in the array are processed successfully, the result will be constantly added to the first numerical object with a zero index.

Now we can recall the working principles of the while loop and identify the difference (recall that in Python, exiting a loop with a postcondition is based on logical criteria - true (the loop continues to work) or false (the loop stops)).

How to handle string value in Python using for construct?

In every programming language there are cycles, and they work, as a rule, on the same principle, the differences are noticeable only in the syntax. However, the for loop in the Python language is not ordinary and trivial, because the principle of its operation is not limited to the counter. This design goes through each element separately. All of this is easy to explain using strings as an example, but first, let's look at the contents of the for loop:

for variable

the variable stores the result of the loop

in variable_2

the in keyword is a prerequisite for working with the for loop. From variable_2 we extract the value that we will iterate. For clarity and clarity, let's look at a small example of how to work and iterate over strings in Python:

char = 'programming' # Declare a variable and assign it a string value

for slovo in char: # Create a slovo variable, which will store enumeration indices from the char variable

print (slovo, end = '^') # Output slovo and after each letter we insert a symbol - a bird.

The result of the script:

P ^ p ^ o ^ r ^ p ^ a ^ m ^ m ^ and ^ p ^ o ^ in ^ a ^ n ^ and ^ e

Continue statement

The continue operator implements the transition to the next cycle specified by the condition, regardless of the remainder in the body of the cycle. You can use the continue operator in two loops - for and while.

Consider an example:

for count in 'repeat each letter except o'

if count == 'o':

continue

print (count * 2, end = '')

The result will be as follows:

Ppvvtrriimm kkazhdyuyuyu bbuukkvvuu, kkrrmmee

When the handler found the letter “o” in the line “repeat every letter except o”, the program execution was immediately redirected to the line after the word “continue”, where, by condition, each letter was duplicated.

Break statement

The keyword “break” is inserted at the place where the loop should be interrupted, without waiting for its completion, which was specified by the condition. This construction is very often used when writing programs with a lot of logic and conditions.

Consider a small example of the break statement:

for count in 'repeat each letter except o'

if count == 'o':

break

print (count * 2, end = '')

The result will be as follows:

pp

When the handler found the letter “o” in the line “repeat every letter except, o”, the program execution was immediately stopped, despite the fact that the next line contains some conditions for the loop.

Magic word else

In a loop of any kind, you can use the else statement. What is it for? It checks whether the exit from the loop was completed with break methods or in the usual way. A block with the given rules inside else will begin implementation only if the loop exits without the break construct.

Consider a small example:

for count in 'hello world':

if count == 'i':

break

else:

print ('Your phrase does not have the letter' I '')

The result of the script:

Your phrase does not have the letter “I”

Reverse-order looping examples in the Python programming language

python reverse loop

How is reverse loop implemented in Python? Let's imagine that we are writing a program that should recognize a character string and print it in reverse order. How to implement this?

Consider the example below:

slovo = 'programming'

new_slovo = []

for count in range (len (s), 0, -1):

new_slovo.append (s [i-1])

new_slovlo

['n', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'and', 'r', 'o', 'in', ' a ',' n ',' and ',' e ']

print (new_slovo)

['n', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'and', 'r', 'o', 'in', ' a ',' n ',' and ',' e ']

print (''. join (new_slovo))

The result of the script:

einavorimmargorp

Nested loops

In the Python programming language, loops also exist nested, that is, placed in the body of another. Each cycle can have its own embedded cycle, and so you can build a staircase to infinity. At the first iteration, the outer loop calls the inner loop, which runs until its completion, then all control is redirected to the body of the outer loop. Each language has its own peculiarities of nested loops, so let's figure out how they work in the Python programming language.

python nested loops

If nested loops are used, Python offers the following syntax:

for variable in sequential variable:

for variable in sequential variable

action (s)

action (s)

python syntax loops

The features of nested loops include the fact that inside a loop of any type, you can also use any type of loop! This means that in a while (or for) loop, a for loop can be nested, or again, while, and vice versa.

Source: https://habr.com/ru/post/K15156/


All Articles