中途停止 while 循环 - Python [英] Stopping a while loop mid-way - Python

查看:41
本文介绍了中途停止 while 循环 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在语句中途停止 Python 中的while"循环的最佳方法是什么?我知道 break 但我认为使用它是不好的做法.

What is the best way to stop a 'while' loop in Python mid-way through the statement? I'm aware of break but I thought using this would be bad practice.

例如,在下面这段代码中,我只希望程序打印一次,而不是两次...

For example, in this code below, I only want the program to print once, not twice...

variable = ""
while variable == "" :
    print("Variable is blank.")

    # statement should break here...

    variable = "text"
    print("Variable is: " + variable)

你能帮忙吗?提前致谢.

Can you help? Thanks in advance.

推荐答案

break 很好,虽然它通常是有条件地使用.无条件使用,它提出了为什么要使用 while 循环的问题:

break is fine, although it is usually used conditionally. Used unconditionally, it raises the question of why a while loop is used at all:

# Don't do this
while condition:
    <some code>
    break
    <some unreachable code>

# Do this
if condition:
    <some code>

<小时>

有条件地使用,它提供了一种提前测试循环条件(或完全独立的条件)的方法:


Used conditionally, it provides a way of testing the loop condition (or a completely separate condition) early:

while <some condition>:
    <some code>
    if <other condition>:
        break
    <some more code>

它通常与其他无限循环一起使用,以模拟其他语言中的 do-while 语句,这样您就可以保证循环至少执行一次.

It is often used with an otherwise infinite loop to simulate the do-while statement found in other languages, so that you can guarantee the loop executes at least once.

while True:
    <some code>
    if <some condition>:
        break

而不是

<some code>
while <some condition>:
    <some code>

这篇关于中途停止 while 循环 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆