Python-在找到字典中的键后停止for循环

Python-在找到字典中的键后停止for循环,python,loops,dictionary,Python,Loops,Dictionary,我需要for循环在usernameMatchbool值更改为False后不再继续查找字典 def username(): usernameMatch = True while usernameMatch == True: print ('Username:') username = input() print ('checking username......\n') for key in usernameDic

我需要
for
循环在
usernameMatch
bool值更改为
False
后不再继续查找字典

def username():
    usernameMatch = True

    while usernameMatch == True:
        print ('Username:')
        username = input()
        print ('checking username......\n')

        for key in usernameDictionary:
            if username == key:
                print('match')
            else:
                usernameMatch == False

正如所有评论所说,使用
break
语句:

for key in usernameDictionary:
    if username == key:
        print('match')
    else:
        usernameMatch == False
        break

你可以阅读更多关于这方面的内容,正如所有评论所说,使用
break
语句:

for key in usernameDictionary:
    if username == key:
        print('match')
    else:
        usernameMatch == False
        break

您可以阅读有关此的更多信息

最后执行以下操作:

def username():

usernameMatch = True

while usernameMatch == True:

    print ('Username:')
    username = input()
    print ('checking username......\n')

    if username in usernameDictionary:
        print("yes")
    else:
        usernameMatch = False

最后做了以下几件事:

def username():

usernameMatch = True

while usernameMatch == True:

    print ('Username:')
    username = input()
    print ('checking username......\n')

    if username in usernameDictionary:
        print("yes")
    else:
        usernameMatch = False

您可以在if语句中使用
break
语句
break
就可以了。但是,请回顾一下Python的基本原理,因为这是基本原理之一。如果不进行一些基础训练,你不会走得太远。顺便说一句,while循环是多余的。此外,还有更简单的方法来检查变量是否为中的键。你可以在if语句中使用
break
语句a
break
就可以了。但是,请回顾一下Python的基本原理,因为这是基本原理之一。如果不进行一些基础训练,你不会走得太远。顺便说一句,while循环是多余的。此外,还有更简单的方法来检查变量是否为中的键。字典