Python“ while”循环不会终止

时间:2020-04-22 12:57:06

标签: python loops while-loop exit

我目前正在一个项目中,我们必须检查密码强度并生成一个强密码,但是在为退出程序提供一种方法的过程中,我遇到了障碍,无法找到解决方法。进展。我尝试过break和sys.exit(),但似乎都没有用。 我想当他们输入[3]然后输入['yes']时,程序结束,但是它只是返回第一个问题。 我还尝试了while = True:,但成功率更低。

count = 0
while (count < 1):

    while True:
        choice = input ("Do you want to: 1) Check a password 2) Generate a Password, or 3) Quit? . [1/2/3]? : ")
        if choice in ['1', '2', '3']:
            break
    if choice == "1":
        while True:
            checkyes = input ("you want to check a password, correct? [yes/no]")
            if checkyes in ['yes', 'no']:
               break
    elif choice == "2":
        while True:
            genyes = input ("you want to generate a password, correct? [yes/no]")
            if genyes in ['yes', 'no']:
                break
    else:
        while True:
            quityes = input ("you want to quit, correct? [yes/no]")
            if quityes in ['yes', 'no']:
                break
                if choice == "yes":
                    count = count + 1
                else:
                    pass

3 个答案:

答案 0 :(得分:1)

您正在为退出条件检查错误的变量。您需要检查quityes

count = 0
while (count < 1):

    while True:
        choice = input ("Do you want to: 1) Check a password 2) Generate a Password, or 3) Quit? . [1/2/3]? : ")
        if choice in ['1', '2', '3']:
            break
    if choice == "1":
        while True:
            checkyes = input ("you want to check a password, correct? [yes/no]")
            if checkyes in ['yes', 'no']:
               break
    elif choice == "2":
        while True:
            genyes = input ("you want to generate a password, correct? [yes/no]")
            if genyes in ['yes', 'no']:
                break
    else:
        while True:
            quityes = input ("you want to quit, correct? [yes/no]")
            if quityes in ['yes', 'no']:
               if quityes == 'yes'
                    count += 1
                    break
               else:
                   pass

输出:

Do you want to: 1) Check a password 2) Generate a Password, or 3) Quit? . [1/2/3]? : 3
you want to quit, correct? [yes/no]yes

Process finished with exit code 0

答案 1 :(得分:1)

2个问题:

  • break语句在递增计数之前执行
  • 您将choice上的quityes改为'yes'

    if quityes in ['yes', 'no']:       
        if quityes == "yes":
            count = count + 1
        else:
             pass
        break
    

答案 2 :(得分:0)

您可以尝试导入sys并将中断替换为sys.exit()。

想想中断没有起作用的原因是因为它脱离了第一个循环,但没有脱离更大的循环。

相关问题