Loop syntax

Loop structure

Loop structure is the structure of while and for loop statements, which can reduce redundant code and improve code efficiency.

The while loop

If the expression is true, then the scope of the block of the while loop will be executed repeatedly. After each execution, the expression will be evaluated again. If the expression is true, then the above steps will be repeated until the expression is false. If it’s false from the start, skip it.

while expression:
    code0
    code1
    ...
Copy the code
Num = 1 # sum_up = 0 # count (count = 100) # count (count = 100) # count (count = 100) Print (num) # print(num) # sum_up += num # print(num += 1) # ', sum_up) # Loop ends, output their sumCopy the code

Infinite loop

As long as the condition expression of a while loop remains true, the corresponding scope will continue to execute and will not be able to escape, forming an infinite loop. When the loop is infinite, the loop cannot break out, and the code after the loop statement does not execute.

While True: print(' infinite loop ') print(' break out of loop 'Copy the code

Keyword use

Let’s talk about three very important keywords: pass, break, and continue

pass

It means a placeholder. The statement itself is empty, has no meaning, does nothing, and occupies some necessary space to maintain the integrity of the program structure.

Note the difference between “None” and “pass.” None means nothing, but it is also false; Pass is not meaningful at all, just to occupy some place to put an error, more often used in the development of the program, the official launch is difficult to see this keyword.

# Code block must have scope, otherwise error, but I don't want to execute anything now, what do I do? If True: pass # use pass as placeholder while True: pass # use pass as placeholderCopy the code
break

Use only in loop statements, such as while or for. As long as this keyword appears, the loop will immediately break and break out of the loop. The code that is not executed in the scope of the loop will not be executed.

While count: count -= 1 if count == 6: break print(count) ""Copy the code
continue

Use only in looping statements. Note the difference between break and continue. Continue skips the current looping statement and continues the execution of the loop.

While count: count -= 1 if count == 6: continue print(count) ""Copy the code

For loop

role

Loop, iterate, iterate. The main purpose of a for loop is to iterate over iterable objects. The data elements in the iterable are extracted one by one, and the code in the code block is executed until the iterable is complete.

Traverse type

Iterable objects: container data, range() functions, iterators.

# for... The variables in the middle are the element data in the iterable. For variable in iterable: code2 code1...Copy the code
Container = 'hello motherland' for I in container: print(I)Copy the code

Traversing a dictionary only iterates through the keys of the dictionary

Dctvar = {'one': 1, 'two': 2, 'three': 3} for I in dctvar: print(I) "; one two three '''Copy the code

To traverse multiple levels of containers, we need to use nested for loops

var = [[1, 2, 3, 4, 5], [12, 34, 56, 67, 84, 55]]
for i in var:
    for j in i:
        print(j)
Copy the code
Unpacking of variables

In the case of the container, we can directly use the same number of variables to extract the data directly from the container.

Print (a, b, c, d, e) a, b = [' motherland', 'motherland'] print(a, b) a, b = {'one': 1, 'two': 2} # print(a, b) ""Copy the code

Therefore, when traversing multi-level containers of equal length, we can use the feature of unpacking variables to traverse the container quickly and try to avoid the nested use of loops, because the nested loop is very consuming computer resources.

var = [[1, 2, 3, 4, 5], [12, 56, 67, 84, 55]] for a, b, c, d, e in var: Print (a, b, c, d, e) ""Copy the code
Range () object

The range function is an iterable that returns numbers in sequence, and can be used with for to simplify complex tasks.

Grammar:

range([start_number], stop_number, step_number)

Range ([start value], end value, [step size])

All three arguments to range are integer numbers, and range can be used in three ways

  1. Enter a parameter that indicates the end value. The returned value ranges from 0 to n-1

    For I in range(5): print(I) ""; 0 1 2 3 4 ""Copy the code
  2. Enter two parameters. The first parameter S is the start value and the second parameter N is the end value. Return S ~~ n-1.

    For I in range(-3, 2): print(I) ""Copy the code
  3. Enter three parameters. The third parameter indicates the step size, which means that the increment of the value is returned in order of the step size.

    For I in range(2, 10, 3): print(I) ""Copy the code

    The bottom

    For I in range(5, 0, -1): print(I) ""Copy the code

conclusion

While loops are usually used in more impetuous logic; A for loop is generally used for traversing data. But the essence of the two is the same.

\