Python program flow control statement: for loop


for loop

Python uses a for loop to traverse any iterable object , obtain the elements in the iterable object in turn, and stop the loop after the last element is obtained.

Basic structure of for loop

The for loop syntax is as follows:

for variable in sequence:
    statements
else:
    statements

The else part can be omitted. Sequence is an iterable object. The for loop sequentially obtains and assigns the elements in the sequence to the variable variable. Each time the loop is performed, the variable is assigned once, until the last element in the sequence is obtained, and the loop ends. The flow chart is shown in the figure:
insert image description here

An example is as follows:

>>> s = [1,2,3,4,5]
>>> for item in s: # 依次将列表中的元素赋值给item,取完最后一个元素5,循环停止
...		print(item)
1
2
3
4
5

After the for loop is executed, the statement block under esle is executed; if the for loop exits halfway, the statement block under else is not executed. The example is as follows:

>>> s = [1, 2, 3, 4, 5]
>>> for item in s:
...    print(item)
>>> else: # for循环正常运行完后会执行else下的语句块
...    print('for循环执行完毕')
1
2
3
4
5
for循环执行完毕   
>>> s = [1, 2, 3, 4, 5]
>>> for item in s:
...    if item < 3:
...        print(item)
...    else:
...        break
>>> else: # for循环被break语句断开,没有运行完,不执行else下的语句块
...    print('for循环执行完毕')
1
2

range() function

The range() function can generate a sequence with the following syntax:

range(start, stop[, step])

parameter:

  • start: start value. The default value is 0, which can be omitted;
  • stop: the end value, excluding the end value;
  • step: the step size, the default is 1.

Return value: range object

The return value of the range() function is a sequence of numbers. The start value can be obtained, but the end value cannot be obtained. It is an interval that is closed on the left and open on the right. This sequence is an iterable object, which can be traversed by using a for loop. It can be converted to a list using the list() function, as an example:

>>> print(range(1, 5)) # 生成开始值是1,结束值是4,步长为1的数列,左闭右开的区间
range(1, 5) # range对象
>>> for i in range(1, 5): # 使用for循环遍历range对象的值
...		print(i)
1
2
3
4

# 使用list()函数将range对象转换成列表输出
>>> s = list(range(5)) # range(5)等同于range(0, 5),开始值默认为0,步长默认为1
>>> print(s)
[0, 1, 2, 3, 4]

Common scope of for loop

The for loop can loop through iterable objects. Multiple variables can be used to iterate sequence objects in the for loop. For example, the tuple returned by the dict.items() method can use two variables to receive the elements in the tuple, An example is as follows:

>>> d1 = {
    
    'name':'lilei', 'age':20, 'grade':'three'}
>>> for k, v in d1.items(): # 使用变量k, v接收元组中的元素
... 	print(k, v)
	
name lilei
age 20
grade three
>>> for (a, b) in [(1,2),(3,4),(5,6),(7,8)]:
... 	print(a, b)

1 2
3 4
5 6
7 8

Nesting of for loops

For loops can be nested, that is, for loops can be used inside for loops, and two or more layers are supported. Examples are as follows:

Example: Printing the nine-nine multiplication table

>>> for i in range(1, 10): 
...    for j in range(1, i + 1):
...        print('%s * %s = %s' % (i, j, i * j), end=' ')
...    print()

1 * 1 = 1 
2 * 1 = 2 2 * 2 = 4 
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81

The variable i in the outer for loop is assigned as: 1, 2, 3, 4, 5, 6, 7, 8, 9 respectively. When i=1, the inner for loop j can be assigned the value: 1. At this point i=1, j=1, and then print '1 * 1 = 1', the print function does not wrap, and the inner loop is executed; execute print() to wrap. The outer loop enters the next layer. When i=2, the inner loop j can be assigned as: 1, 2. When the inner loop loops for the first time: i=2, j=1, print '2 * 1 = 2', the print function does not wrap, and the inner loop performs the second loop: i=2, j=2, print ' 2 * 2 = 4', the inner loop ends, and print() is executed to wrap the line. The outer layer loops to the next layer, i = 3...

By analogy, the outer layer circulates one layer, the inner layer circulates once, and after the inner layer cycle ends, the outer layer cycle can enter the next layer.

For loops and if conditional statements can also be nested, examples are as follows:

Calculate the sum of numbers between 1 and 100 that are divisible by 3

>>> s = 0
>>> for i in range(1, 101):
...		if i % 3 == 0: # 满足if条件的执行求和
...			s += i
>>> print(s)
1683

Guess you like

Origin blog.csdn.net/shield911/article/details/124183534