ComputersProgramming

Python programming language: loops

In the Python programming language (also "Python" or "Python"), there are several ways of looping some action. The main tools for implementing an iteration in Python are the while and for loops. The while loop is more universal than for, so it runs slower. However, this does not mean that it is better! The for loop is used much more often, because with its help the most complex tasks for creating multi-level and multi-conditional programs are implemented.

Python: A cycle with a postcondition

Cycles with a postcondition are loops while they are the most universal organizational constructs in a given programming environment. The while loop operates on a "as long as" basis. This means the following: while some condition will return the true value, it will work! This design is called a "cycle", because the functional control is cyclically repeated, starting with the original value. Exiting the while loop in Python will be implemented at the moment when the value becomes false. At this point, the interpreter passes the execution of the program to the next functional-semantic segment, that is, a new line, which is located after the block with a while.

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

1. While (condition):

2. the expression

The expression can be either one instruction or several. A condition is always a certain true value or a nonzero value. Such a construction works as long as the given condition is true.

Using the while loop in Python by example

We will explain the while loop. Python quite structured its iterations:

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", our cycle will be executed until it becomes false.

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

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

A
A
A
A
A
A
A

An infinite while loop in Python

How do I make an infinite while loop in Python? It is not difficult to guess at all, because the cycle works until it gets a false value, and if this value simply does not exist? The answer to the question is probably already clear to everyone. In which cases is an infinite cycle necessary to solve a problem? This example is the implementation of a program such as "clock". Undoubtedly, you will need to use an infinite loop, which will permanently update and display the time.

An infinite loop is often a mistake for novice programmers who forget to add changes to the loop conditions.

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

Number = 1 # declare the variable number and assign it the value 1

While number <10: # create a postcondition, in which the number is less than 10

Print 'Hello' # execute the condition (print the message "Hello")

Such a program should not be in a hurry to compile, because it will be executed indefinitely. We have set such conditions under which there will never be a false value: the condition "number <10" in this case is invariable and true, so the iteration will be carried out continuously, displaying the N-th number of "Hello" messages. To stop the process of perpetual compilation, you will need to press Ctrl + C in the shell.

Python: syntax. The while and for loops

As mentioned above, in the Python programming language, there are several ways to organize repetition of a group of expressions. The for loop is a for loop that 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. A lot of ways to solve and speed of this design a little benefit from a cycle with a postcondition, so it is much more often used to perform a multitude of trivial tasks.

What are the tasks before the for loop? Undoubtedly, the same as while - iterate any processes. In the programs executed on Python, the for loop is extensively used, which is able to implement the bypass of a given set of elements and perform various iterations over them in its body. The possibilities of this construction can be applied when processing strings or lists in the same way as any other iterated object.

Example of using the for loop in Python

Suppose we have a list of numbers, and we need to increase each element (that is, a number) by three units. We can implement such a task by looping, for.

Let's look at a small example where we will perform the corresponding actions (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 counter with zero value

For elements in spisok_chisel: # we go through 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 the index

The result of the above construction will be:

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

In our example, there is a variable count, which we need to mark the changing values in the array "spisok_chisel". The variable count records the index values of each element in the array (each number in the list). The variable "elements" associates the resulting values in the list. In the for loop, we observe how the processing of each numeric object in the list is implemented. Inside the loop, each numeric object with the "count" index is appended with the sum of the current iterated element and the triplet. Then our index "count" is incremented by one, and the flow of the program implementation is returned to the beginning of the declaration for. 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 the condition, the cycle process will be completed. Let's pay attention to one more nuance: if you do not write the line "count = count + 1", despite the fact that the array objects are successfully processed, the result will be constantly added to the first numeric object with zero index.

Now we can remember the principles of the while loop and find out the difference (we recall that in Python, the exit from the loop with the postcondition is performed based on logical criteria - true (the loop continues to work) or false (the loop stops)).

How to handle a string value in Python using the for construct?

In each programming language, there are cycles, and they work, as a rule, according to the same principle, the differences are noticeable only in the syntax. However, the for loop in the language "Python" is not ordinary and trivial, because the principle of its work is not limited to the counter. This design traverses each element separately. All this is easy to explain with the example of working with strings, but first let's look at the composition of the for loop:

For a variable

The variable stores the result of the cycle

In variable_2

The keyword "in" is a mandatory condition when working with the for loop. From variable_2 we extend the value, which we will iterate. For clarity and clarity, let's look at a small example of how to work and stroke the lines in Python:

Char = 'programming' # Declared a variable and assigned it a string value

For slovo in char: # Create a variable called slovo, which will store indexes from the variable char

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

The result of the script:

N ^ p ^ o ^ r ^ p ^ a ^ m ^ m ^ and ^ p ^ o ^ in ^ a ^ n ^ u ^ e

The 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 loop. You can use the continue statement in two loops - for and while.

Consider an example:

For count in 'we will repeat each letter, except for o'

If count == 'o':

Continue

Print (count * 2, end = '')

The result is as follows:

Ппввттрриймм ккаажжддууюю ббууккввуу ,, ккррммее

When the handler found the letter "o" in the line 'repeat every letter except for o', the program execution was immediately redirected to the line after the word 'continue', where by condition it was specified to duplicate each letter.

The break statement

The keyword "break" is inserted in the place where the loop should be interrupted, without waiting for its completion, which was set by the condition. This design 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 'we will repeat each letter, except for o'

If count == 'o':

Break

Print (count * 2, end = '')

The result is as follows:

Pp

When the handler found the letter "o" in the line 'repeat each letter except, o', then the execution of the program was immediately stopped, despite the fact that the next line contains some conditions for the cycle.

The magic word else

In a loop of any kind, you can use the else clause. What is it for? It checks whether the break was made by the break methods or by the usual way. A block with the specified rules inside the else will start implementation only if the exit from the loop was implemented without using the break construct.

Consider a small example:

For count in 'hello world':

If count == 'I':

Break

Else:

Print ('Your letter does not contain the letter "I")

The result of the script:

In your phrase there is no letter "I"

Examples of reverse-order loops in the Python programming language

How is the 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', 'p', 'o', 'r', 'p', 'a', 'm', 'm', 'and', 'p', 'o', 'in' A ',' n ',' and ',' e ']

Print (new_slovo)

['N', 'p', 'o', 'r', 'p', 'a', 'm', 'm', 'and', 'p', 'o', 'in' A ',' n ',' and ',' e ']

Print (''. Join (new_slovo))

The result of the script:

Einavorimargorp

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 enclosed loop, and so you can build a ladder to infinity. At the first iteration, the outer loop calls the internal loop, which executes before its completion, then all control is redirected to the body of the outer loop. Each language has its own peculiarities of nested loops, let's see how they are arranged in the programming language "Python".

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

For a variable in a sequential variable:

For a variable in a sequential variable

Action

Action

The peculiarities of nested loops include the fact that any type of cycle can be used within a cycle of any type! This means that in the while (or for) loop, a for loop can be nested or, again, while and vice versa.

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.delachieve.com. Theme powered by WordPress.