繁体   English   中英

如何正确使用 While 循环而不让它在中断时重复

[英]How Can I Properly Use While Loop And Not Have it Repeat On Break

在尝试创建一个 while 循环时,我遇到了一个令人困惑的问题,即中断没有按预期工作。 预期的行为是,一旦在 Mongo DB 中找到配置文件名称,while 循环就会中断并执行脚本的其余部分。 如果找到配置文件名称,则循环应重新开始并要求用户重新输入其配置文件名称。

下面是 while 循环的例子。

while True:
    profile_name = input("\nEnter Profile Name (Case Sensitive): ")
    if len(profile_name) == 0:
        print("Profile cannot be blank!\n")
        pass
    for profile in prof_collection.find({"name": profile_name}):
        if profile_name in profile["name"]:
            print("%s has been found." % profile_name)
            break
        else:
            print("%s was not found. Please enter a valid Profile." % profile_name)
            pass

这里的任何帮助将不胜感激。

您可以将变量设置为标志。

looper = True # the flag
while looper:
profile_name = input("\nEnter Profile Name (Case Sensitive): ")
    if len(profile_name) == 0:
        print("Profile cannot be blank!\n")
        pass
    for profile in prof_collection.find({"name": profile_name}):
        if profile_name in profile["name"]:
            print("%s has been found." % profile_name)
            looper = False # flag changes
            break
        else:
            print("%s was not found. Please enter a valid Profile." % profile_name)
            pass

暂无
暂无

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

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