The for loop: examples and possible errors

In computer science, the for loop is used to do the same thing many times. For example, remove the product from the list one by one, sort out the numbers in a certain range and execute the corresponding script for each of them.

The for loop, unlike while, is used most often. Both options exist in all programming languages. In a number of PLs, it is syntactically and semantically identical.

In python, a for loop consists of:

  • operator for;
  • the name of the variable to be assigned;
  • list being processed;
  • function bodies and additional operators.

Unlike C-like languages, instructions are not separated by curly braces {}. To do this, use the operator “:” after the block of conditions and tabulation in the body of the loop. Without indenting tab, the code will not work and an error will appear.

As additional operators, continue, break, pass are used - pointers to skip the iteration, end the loop, skip the iteration. They are indicated after a block of some if-else conditions.

For loop

Such a loop is used to iterate over all elements of a collection. Set in the format

for variable in list: instruction

Cycle diagram

It resembles a foreach loop from C ++

foreach (type item in set) {}; for i in 'hello world': print(i * 2, end='') hheelllloo wwoorrlldd 

In Python, the for loop is collaborative — body instructions are executed for each member of the list without explicitly specifying a sequence. The execution of the instructions occurs in the most optimal order.

Variable i is assigned each object from the collection. List items can be numeric or string, but always an integer type. When working with multidimensional arrays, the variable i will be understood as nested arrays.

 list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]] for list in list_of_lists: print(list) ['hammerhead', 'great white', 'dogfish'] [0, 1, 2] [9.9, 8.8, 7.7] 

To display each element of a nested array, you must use nested loops.

Continue

The operator allows you to skip part of the for loop and move on to the next iteration. This is done when an external factor occurs. Continue is indicated after the optional if block, but the condition itself is inside the loop before the main statement.

 number = 0 for number in range(10): number = number + 1 if number == 5: continue #   continue print(str(number)) print('End') 

Each number in a list of values ​​from 0 to 10 increments the variable number, which is initially zero. When number gets the value 5, the loop will break and the next iteration will begin. It will turn out:

 1 2 3 4 6 7 8 9 10 End 

Break

The operator is used in conjunction with the if condition. This design completely interrupts the cycle when a factor occurs.

Loop abort statement
 number = 0 for number in range(10): number += 1 if number == 5: break # break print('Number = ' + str(number)) print('Out of loop') 

Here, the if statement defines a condition: if the value of the variable number is 5, the loop breaks. At each iteration, the first print () method is executed and displays a notification

 Number = 5. 

When the loop is stopped by the break statement, the following print () method is executed.

Another example checks if the second number is divisible by the first without a remainder.

 for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: # loop fell through without finding a factor print(n, 'is a prime number') 

In this case, a nested loop is used. First, all members of a plurality of numbers ranging from 2 to 10 are accepted as n. For each n, a new list is defined with items from 2 to n. Thus, we have 8 arrays of different lengths. All elements from the resulting collections are set by the variable x. Now the if condition checks that the result of n / x is an integer value. If true, the loop breaks and displays a message. If n / x is divided with the remainder, another message is displayed.

Pass

The operator is needed to ignore additional conditions.

 number = 0 for number in range(10): number += 1 if number == 5: pass print(str(number)) print('End') 

The program works as if the condition if number == 5 does not exist. Appears on the monitor

 1 2 3 4 5 6 7 8 9 10 End 

We see that nothing happens during the execution of the pass statement. It is used as a stub only where syntactically necessary. For example, when developing a new class with methods that do not need to be implemented.

 class MyClass(object): def meth_a(self): pass def meth_b(self): print "I'm meth_b" 

The meth_a function does not yet have its own instruction. But Python requires that the blocks of code if, except, def, class are not empty. Otherwise, an error message appears.

 IndentationError: expected an indented block. 

Instead, you can specify pass.

 class CompileError(Exception): pass 

Another purpose of using the pass statement is to explicitly do nothing.

This can be seen in another example of the for and pass loop :

 for t in range(25): do(t) if t == 20: pass 

In this code snippet, list items from 0 to 25 are sorted. They are considered as a variable t. At each iteration, some do () function is executed. If you want nothing to happen on a certain value, pass is indicated. For example, the do function displays a message 24 times and skips the instruction at t = 20.

Arrays

Programs with a for loop help create some sequence of values ​​and assign them to variables.

Arrays and Loop

The following record is possible:

 for i in [0, 1, 2, 3, 4, 5]: print i**2 

If the list had more elements, it would be more rational to create a separate array.

 array = [1, 2, 3, 4, 5, 6, 7, 8, 9] for in array: print i 

To create lists like

 array = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

, in Python there is a range () function. The range () method in the parameter area takes three arguments: start value, end, step. Only the last element of the list is required. Thus, range (5) will mean that the array includes numbers from 0 to 5. If you specify a step, then you need to determine the initial element.

 range(0, 10, 2) 

We get:

 0, 2, 4, 6, 8, 10 

Lists of Rows

Work with such lists is similar to numerical. For example, there is a list

 colors = ['red', 'green', 'blue', 'yellow'] 

Developers accustomed to C can write the following function.

 for i in range(len(colors)): print colors[i] 

The code will execute without errors, but a more correct use of the for loop looks like this:

 colors = ['red', 'green', 'blue', 'yellow'] for color in colors: print color 
Array creation

If you need to go through the list from the last to zero, the reversed () function is used.

 colors = ['red', 'green', 'blue', 'yellow'] for color in reversed(colors): print color 

The following entry is erroneous. Again, this came from the C language.

Lists and Indexes

Python has built-in enumerate () functions for working with array indices. They are useful in python for loops.

Arrays and Index

The argument is a sequence of values. The enumerate () function simplifies the use of the following code:

 for i in range(len(L)): item = L[i] # ... compute some result based on item ... 

The len () method is used here. It returns the number of elements, in this case, an array L. The many elements are taken as an argument to the range () function. Thus, we define the list [0, ... n].

Using L [i] we get access to each element of the array L.

 L[0], L[1], L[2]  .. 

The enumerate () function eliminates the need to initialize the counter variable b and simplifies writing to

 for counter, value in enumerate(L): print(“index : “counter, “value : “value) 

Enumerate () returns a counter-element pair, so two variables are specified with the for loop operator.

The items () and iteritems () functions, which are used as methods, are similar.

 d.items() d.iteritems() 

Two lists

When you need to use members of multiple lists, the zip () function is used.

Array join

It takes list A and list B, makes them into a single zip object that contains nested tuples. Each element of the new object connects the members of lists A and B and sorts them by index.

 zip_object[1] = [A[1], B[1]]; 

If 4 arrays are specified at the zip () input, the elements of the zip array will contain 4 elements. Packing arrays of different lengths does not cause an error. Only elements that contain a pair value will be placed in the new object.

To include every element in the tuple, even one that does not have a pair, zip_longest () is used.

 list(itertools.zip_longest((1,2,3), [4])) #[(1, 4), (2, None), (3, None)] 

Key Sort

When you need to not just walk through the elements of an array, but modify it, the keys () function is applied.

Key is Value

The method duplicates and returns a list of available dictionary keys.

 for k in d.keys(): if k.startswith('R'): del d[k] 

There is an array d. Its elements are copied using the keys () method. Each element is a variable k. It is processed using startswith; upon coincidence, the element is deleted from the main array.

startswith () returns a flag that checks whether the line starts with the specified prefix. The function has three arguments: prefix, start, end.

 str.startswith(prefix[, start[, end]]) -> bool 

Only the first is required - prefix. It can be a string or a tuple.

 my_str.startswith('value') 

or

 my_str.startswith(('value1', 'value2')) 

If you need to specify several lines in the parameter field, the elements are wrapped in additional brackets ().

The start argument indicates the index of the element at which the count begins. Positive and negative values ​​are supported. If start = -x, then the search begins with an element with index x from the end. The end parameter indicates the last character at which line analysis stops. It also supports negative values. With end = -x, the last member of the list is index x from the beginning.

Similar to startswith (), the endswith () function works. It checks to see if the line ends with the specified postfix. It has three parameters suffix, start, end, also returns a boolean value.

Merging Lists

If you need to connect the elements of two arrays, the fastest way is to use a bunch of dict methods (izip (array 1, array 1)). In this case, the elements are not arranged sequentially one after another, but in the form:

 '  1' : '  2' 
 names = ['raymond', 'rachel', 'matthew'] colors = ['red', 'green', 'blue'] d = dict(zip(names, colors)) # {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'} 

The dict () method creates a dictionary, inside of which values ​​are placed in the above way - through “:”. The element of array 2 is used as the main value. To call it, you need to access it by index - the value of array 1.

 d['raymond'] # red 

Counting List Members

To find out how many elements a list consists of, the get () function is used.

 d.get(key, default = None) 

This method checks the dictionary d for the presence of key, returns the index key [index].

 colors = ['red', 'green', 'red', 'blue', 'green', 'red'] d = {} for color in colors: d[color] = d.get(color, 0) + 1 

The get () method is a more convenient and faster analogue of the following code.

 colors = ['red', 'green', 'red', 'blue', 'green', 'red'] d = {} for color in colors: if color not in d: d[color] = 0 d[color] += 1 

These are basic examples and possible for loop errors.

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


All Articles