Summary of Differences between while and for in python

  • 2021-07-03 00:39:10
  • OfStack

There is no difference between for cycle and while cycle in Python, but in practical application, it is not targeted.

The while loop is suitable for loops with unknown number of loops, and the for loop is suitable for loops with known number of loops.

for is mainly used in traversal, such as:


for i in range(10):

  print(i)

 The printed result is: 

0 1 2 3 4 5 6 7 8 9  

list1 = [1,2,"a " ]

for i in list1:

  print(i)

# Print as a step-by-step list list1 Elements in: 

1

2

a

However, while loop is rarely used for traversal (there are too many statements, which is not as convenient as for), and while is mainly used to judge the loop under the conditions, such as:


i = 0

while True:

  if i<3:

    print(i)

    i += 1

  else : 

    print("i>=3 La !")

    break

# Run result: When i Overlay to 3 Before, print in turn i Value of, when i Equal to 3 Judge that the statement is not true and execute it else Statement, jump out while Cycle 

# Print results: 

0

1

2

Extension instance:


while循环应用举例:
#为什么要用循环?循环可以使需要重复的代码只写1遍即可
a=10
#只要条件成立,就去执行条件后的代码块,条件不成立,直接跳过
while a==10:
 #第1种结束while循环的方式,更改循环的条件,让条件不成立
 number=input('请输入数字,输入0结束while循环:')
 #%s 通用占位符
 #如果字符串中只有1个占位符,可以将变量直接写在%之后
 #如果字符串中有两个或者两个以上的占位符,必须写在%之后,添加小括号(),将占位的变量写在小括号内
 print('您输入的数字为%s'%number)
 if number=='0':
  #更改a的值,让其不等于10
  a=20
#第2种结束while循环的方式 使用break关键字结束循环
#True 布尔类型的数据 True(真 可以使用数字1表示)和False(假 可以使用数字0表示)
while True:
 number=input('请输入内容,输入0结束循环:')
 if number=='0':
  #break跳出当前循环,结束while循环
  #break可结束for循环,也可结束while循环,结束离自己最近的循环
  break

for Examples of circular application (99 Multiplication table )
#coding:utf-8
#python In for Cycle 
#for  Specify the number of cycles 
# Utilization for Cycle   Output 99 Multiplication table 
# Output range, including 5 , excluding 10
#for x in range(5,10):
# print x,
for i in range(1,10):
 for j in range(1,i+1):
  # print ('%s*%s=%s'%(i,j,i*j))
  #\t Represents tabulation, aligning vertically 
   print(' %d*%d=%d'%(j,i,j*i),end="")
  # print j, "*", i, "=", i * j,' ',
 # Line break 3 Ways: Methods 1 print \  Method 2 print '\n'  Method 3 : '\r'
 print('\r')


Related articles: