Skip to main content
 首页 » 编程设计

python之为什么继续不起作用

2025年05月04日11lovecherry

在寻找continue 的过程中,我想编写一个包含break 和continue 的简单循环。我知道 break 结束循环,但我不明白为什么 print('Why won't this ever print!') 从未被触发。

In [21]:  
import random 
 
while True: 
    n = random.randint(0,5) 
    if n == 5: 
        print('It is 5!') 
        break 
    else: 
        print('It is not 5!') 
        continue 
    print('Why won't this ever print!') 
 
Out [21]: 
It is not 5! 
It is not 5! 
It is 5! 

如有任何帮助,我们将不胜感激。

请您参考如下方法:

continue将执行流返回到循环顶部以进行另一次迭代。它不会在循环中继续相同的迭代。

如果您要删除 continue 语句,则 Python 会继续执行下一条语句,并打印 'Why won '这曾经打印过!。