简体   繁体   English

如果条件为 False,如何打破 while 循环?

[英]How to break the while loop if the condition is False?

I have a long function in which I am checking for different parameters and if any of the parameters is False, I don't want to execute the code further.我有一个很长的 function ,我在其中检查不同的参数,如果任何参数为 False,我不想进一步执行代码。

For your understanding, this is how I want to make it work为了您的理解,这就是我想让它工作的方式

Email = True
while(Email == True):
    print("Execute Me")
    Email = False # Break the while loop here
    print("Never execute me")

Here is the pseudo version of my code:这是我的代码的伪版本:

def users_preferences(prefs):
    for pref in prefs:
        send_email = True
        while(send_email == True):
            # Set send_email = False if email is not verified and don't move to the next line
            # Set send_email = False if user's email is not a part of specific group
            ...
            ...

How can I break the loop if the condition is False at any point without further executing the code?如果条件在任何时候为 False,我如何在不进一步执行代码的情况下打破循环?

Edit: The problem with break statements is that it will become cumbersome to check the condition before running a new statement where you have number of statements编辑: break语句的问题在于,在运行具有多个语句的新语句之前检查条件会变得很麻烦

You can use a normal break statement:您可以使用正常的break语句:

Email = True
while Email:
    print("Execute Me")
    Email = False # Break the while loop here
    if not Email:
        break
    print("Never execute me")

Edit: If the while loop doesn't do anything special, the code can be modified to be:编辑:如果while循环没有做任何特别的事情,代码可以修改为:

for pref in prefs:
    if not is_email_verified(email) or not is_user_in_group(user, group):
        continue
    send_email(email)

Hello your code needs to be better indented.您好,您的代码需要更好地缩进。 Also why haven't you tried using break statement to get out of the loop?另外,您为什么不尝试使用 break 语句来跳出循环?

Email = True
while Email:
    # do something
    break
# continue doing something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM