Home  >  Article  >  Backend Development  >  The difference between while and for in python

The difference between while and for in python

(*-*)浩
(*-*)浩Original
2019-06-28 15:14:0910285browse

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.

The difference between while and for in python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn