Python Programming - loop statements (for, while the use of nested loops and Detailed)

for loop Repeat statement. For use in the case of loop cycles it is known, and can achieve all the for loop while loop.
while loop Iteration of the loop in a given condition is true, otherwise exit the loop. In an unknown number of cycles is to use a while loop.
Nested loop Nested loop circulation.

A, for circulation

The for loop can be used to traverse an object (traversal: Popular speaking, it is the first element of this cycle to the last two elements in order to access it again).

1, for recycling scenarios

  • We want an operation is repeated and the number of cycles is known to use a for loop;
  • All No cycle can be achieved while using.

2, syntax

for i in 一组值:          #一组值可以是除数字以外的基本类型
	要执行的操作

3, for example cycling

for loop through the data base type may be other than numbers, such as a string, a tuple, a list, a set of dictionaries, and other files. We can also iterate through the sequence index. Specific operation is as follows:

1> for the string loop iterates
#for循环遍历字符串
str='abc'
for i in str:
	print(i)

结果如下:
a
b
c
2> for loop iterates tuple
tup1=(31,29,31,30,31,30,31,31,30,31,30,31)
for i in tup1:
    print(i,end=' ')   #end=' ' 不换行
 
结果如下:
31 29 31 30 31 30 31 31 30 31 30 31
3> for loop iterates through the list
Fruits=['apple','orange','banana','grape']
for fruit in Fruits:
    print(fruit)
 
结果如下:
apple
orange
banana
grape
4> for looping through the set of
set1={'lisi',180,60,99}    
for i in set1:
    print(i)
 
结果如下:
lisi
99
180
60
5> for loop iterates Dictionary

Note: Python dictionary (Dictionary) items () function to return may traverse the list (key, value) tuples array.

dict1={'name':'lisi','height':180,'weight':60,'score':99}
for k,v in dict1.items():    #遍历字典dict1中的键值对  
    print(k,'--->',v)
print('--------------')  
for k in dict1.keys():       #遍历字典dict1中所有的键
    print(k)
print('--------------')     
for v in dict1.values():     #遍历字典dict1中所有的值 
    print(v)
 
结果如下:
name ---> lisi
height ---> 180
weight ---> 60
score ---> 99
--------------
name
height
weight
score
--------------
lisi
180
60
99
6> traverse file
for content in open("1.txt"):   #当前目录下的1.txt
    print(content)
 
结果如下:
朝辞白帝彩云间,千里江陵一日还。
 
 
 
两岸猿声啼不住,轻舟已过万重山。
7> for 1-9 cycles to achieve even by
sum = 1
for i in list(range(1,10)):   #range序列含左不含右
    sum *= i
print("1*2...*9 =",sum)
 
结果如下:
1*2...*9 = 362880
8> In addition to the above, we also can be traversed by a sequence index

Usage range: range (5) -> parameters. 1, starting from 0 to 5 5 does not contain (i.e. including the left and right free); range (5,15) -> 2 parameters, starting from 5 to 15 does not include 15; range (5,55,5) -> 3 parameters, from 5 to 55 does not contain the start 55, the last parameter is 5 steps.

We use the following examples are built len ​​() function and Range (); len () function returns the length of the list, i.e. the number of elements. range returns a sequence of integers.

fruits = ['banana','apple','mango','grape']
for index in range(len(fruits)):
   print('当前水果 :', fruits[index])
 
结果如下:
当前水果 : banana
当前水果 : apple
当前水果 : mango
当前水果 : grape

Two, while circulation

while loop, as long as the conditions are met, continuous cycle, the loop exits when the condition is not satisfied. Wherein execution statement or statements can be a single block of statements; determination condition can be any expression, in any non-zero value, or empty (null) are True.

Note: to determine the conditions of the while loop is a boolean expression!

1, syntax

while  判断条件:        #判断条件boolean类型的表达式
	执行语句

2, while loop operation example:

1> request even-numbered 1 to 100 and
n=1
sum=0
while n <= 100:
    if n%2==0:
       sum += n
    n=n+1
print('1到100的偶数和为:',sum)
 
结果如下:
1到100的偶数和为: 2550

2> All multiple print within 1-1003 and 5, a multiple of 3, and multiples of 5:

n=1
bei3_5=[]
bei3=[]
bei5=[]
while n<=100:
    if (n%3==0)and(n%5==0):
        bei3_5.append(n)
    elif n%3==0:
        bei3.append(n)
    elif n%5==0:
        bei5.append(n)
    n=n+1
else:                                     #while...else 在条件语句为false时执行else块
    print('1-100内是3和5的倍数有:',bei3_5)
    print('1-100内是3的倍数有:',bei3)
    print('1-100内是5的倍数有:',bei5)
    print('循环结束')
 
结果如下:
1-100内是3和5的倍数有: [15, 30, 45, 60, 75, 90]
1-100内是3的倍数有: [3, 6, 9, 12, 18, 21, 24, 27, 33, 36, 39, 42, 48, 51, 54, 57, 63, 66, 69, 72, 78, 81, 84, 87, 93, 96, 99]
1-100内是5的倍数有: [5, 10, 20, 25, 35, 40, 50, 55, 65, 70, 80, 85, 95, 100]
循环结束

Summary: for and while loops, the similarities between the two that can do a repeat cycle of thing; except that, for the cycle sequence is stopped at the end, while circulation is stopped when the condition is not satisfied.

Third, the nested loop

Python language allows a circulation loop embedded inside another. May for (while) for nested loop (while) loop, may be embedded in the other loop, such as a while loop may be embedded in the loop for the loop body, and vice versa, you can embed in a for loop while loop.

. 1> for loops for nested loop -> Print multiplication tables
for i in range(1,10):
    for j in range(1,i+1):
        print(j,'*',i,'=',(j*i),end='\t')
    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

Guess you like

Origin blog.csdn.net/weixin_45116657/article/details/93745247