while 和 for 循环有什么区别

时间:2021-04-01 04:20:18

标签: python for-loop while-loop

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)

谢谢。

1 个答案:

答案 0 :(得分:1)

一般来说,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()

这个问题在this stackoverflow

中得到了很好的回答

提取信息:

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

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

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

相关问题