首页 > 解决方案 > while 和 for 循环有什么区别

问题描述

python中的while和for之间真的有区别吗?或者我可以使用我想要的任何人吗?我的第二个问题:-

persons['alic', 'sam', 'rain']
first_name = 'mike'
for first_name in persons :
    #when the program runs for the first time
    #what is the value of first_name?
    #is it 'mike',or its value is Null??

    print(first_name)

谢谢。

标签: pythonfor-loopwhile-loop

解决方案


通常,for in 循环对于在已知集合上进行迭代很有用,并且迭代次数是预先确定的。当退出条件是状态变化而不是预定长度时,通常使用 while 循环。

while 循环的常见用例包括:

运行程序的主循环直到键盘中断:

    try:
        while True:
            break
    except KeyboardInterrupt:
        print("Press Ctrl-C to terminate while statement")
        pass

查找引用列表中的最后一个节点:

while(node is not None):
    node = node.next()

这个问题在这个stackoverflow中得到了很好的回答

提取信息:

while 循环- 用于循环直到满足条件以及不确定代码应该循环多少次

for 循环- 用于循环直到满足条件,但在您知道代码需要循环多少次时使用

do while loop - 在检查 while 条件之前执行一次循环的内容。


推荐阅读