Python Lesson Loop Statement

Today I will show you the loop statements in Python

definition

循环语句允许我们执行一个语句或语句组多次

type

Python provides two different types of loops

  • for loop: execute statement repeatedly
#打印1-10
for num in range(1,10):
   print(‘当前是%d’%num)
  • while loop: executed if the condition is True, otherwise not executed
#输出1-10
i = 1
while i < 10:   
    i += 1
    print i     

As can be seen from the above examples,
for is a collection-like operation that loops through a specified range;
while is a loop body that continues to execute the loop body under certain conditions as long as the conditions are met.
The two loops are suitable for different scenarios

control statement

  • break: terminate the loop and jump out of the entire loop
#i==5退出循环,不会走到9
i = 0                    
while i < 10:              
   print '当前值 :', i
   i = i + 1
   if i == 5:   # 当i等于 5 时退出循环
      break
  • continue: Terminate the current loop, jump out of the loop, and execute the next loop
#不会输出字母h
for letter in 'Python':     
   if letter == 'h':
      continue
   print '当前字母 :', letter

Control statements are all used inside loops. Both for and while can be used. In some special needs, different types of termination operations are required. In this case, control statements are needed to terminate this loop or terminate all loops.
Usually used 必须together if语句.

Nested loops

As the name suggests, loops can use multiple layers to meet complex needs. They can also be used in combination with different loops to achieve more complex loop structures, and can be combined with control statements to realize the exit of different nodes.

#循环数据19遍Python字符串
i = 1
while(i < 20):
	i = i + 1
	for letter in 'Python': 
   		print("第%s遍当前字母: %s" %(i , letter))
   

Guess you like

Origin blog.csdn.net/VincentLee7/article/details/128461298