Home > Article > Backend Development > The difference between while and for in python
There is essentially no difference between the for loop and the while loop in Python, but in practical applications, the pertinence is different.
The while loop is suitable for loops with an unknown number of loops, and the for loop is suitable for loops with a known number of loops.
for is mainly used in traversal, such as: (recommended learning: Python video tutorial)
for i in range(10): print(i) 打印结果为: 0 1 2 3 4 5 6 7 8 9 list1 = [1,2,"a”] for i in list1: print(i) #打印结果为逐步列表list1中的元素: 1 2 a
The while loop is rarely used for traversal (too many statements, not as convenient as for), while is mainly used to judge the loop when conditions are met, such as:
i = 0 while True: if i<3: print(i) i += 1 else: print("i>=3啦!") break #运行结果:当i叠加到3前,依次打印i的值,当i等于3的时候判断语句不成立,执行else语句,跳出while循环 #打印结果: 0 1 2
For more Python related technical articles, please visit Python Tutorial column to learn!
The above is the detailed content of The difference between while and for in python. For more information, please follow other related articles on the PHP Chinese website!