gpt4 book ai didi

python - 在 Python 中跳出 while 循环后的流程控制

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:41 29 4
gpt4 key购买 nike

我对编程和 Python 都很陌生。现在有几次,我创建了一个感觉很尴尬的程序流程,我想知道我是否遵循了最佳实践。这在概念上是我想做的:

def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
now do a thing once, but only if you never broke out of the loop above

我最终所做的工作有效,但不知何故感觉不对:

def pseudocode():
while some condition is true:
do some stuff
if some condition is met:
some_condition_met = True
break out of the while loop

if some_condition_met is False:
do a thing

有没有更好的办法?

最佳答案

您正在寻找 while-else循环:

def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke out of the loop above

来自文档:

while_stmt ::=  "while" expression ":" suite
["else" ":" suite]

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

关于python - 在 Python 中跳出 while 循环后的流程控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802815/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com