应用中断条件后循环不会停止

2024-10-04 03:17:18 发布

您现在位置:Python中文网/ 问答频道 /正文

因为我是python的新手,所以我试图做一个练习,其中包含while循环。 我已经写了一段代码,要求用户输入他的详细信息。 在获得所有详细信息后,程序应该停止,但在我的情况下,在输入帐号后,它再次开始要求手机号码输入

请看一下代码,并指出我的错误所在

bnkName = ["SBI", "PNB", "CBI", "ICICI", "BOB"]
targetattmpt = 10
appliedattmpt = 1
while (appliedattmpt <= targetattmpt):
    mobilenum = input("Please Enter your Mobile Number:\n")
    if (len(mobilenum) == 10):

        while (True):
            Bankname = input("Please Enter your Bank Name\n").upper()
            if Bankname in bnkName:
                print("Valid Bank\n")
                print("Please enter your Account Number\n")
                accnum = input("Account Number:\n")
                print(accnum)
                break

            else:
                print("Invalid Bank")


    else:
        print(mobilenum, "IS NOT VALID!!!", "You have", targetattmpt - appliedattmpt, "attempts left\n")
        appliedattm = appliedattm + 1

if (appliedattmpt > targetattmpt):
    print("Account locked!!")

Tags: 代码numberinputyourif详细信息accountbank
1条回答
网友
1楼 · 发布于 2024-10-04 03:17:18

内部循环内的break语句将中断内部循环,但不会中断外部循环。您应该重新考虑逻辑,也许可以添加bool变量来检查内部循环是否中断,这样您就可以中断外部循环。For/while循环有else语句,用于检查循环调用是否成功完成或中断中止。在while循环中,如果中的条件不再为true,则将执行else。 看看:https://book.pythontips.com/en/latest/for_-_else.html

举个例子:

j = 0
bank = True
while(j < 2):
    print('check_this')
    i = 0
    while(i < 2):
        print('check that')
        if bank:
            break
        else:
            i += 1
    else:
        break
    print('I checked both !')
    j += 1

输出:

check_this
check that
I checked both !
check_this
check that
I checked both !

现在将银行更改为False

j = 0
bank = False
while(j < 2):
    print('check_this')
    i = 0
    while(i < 2):
        print('check that')
        if bank:
            break
        else:
            i += 1
    else:
        break
    print('I checked both !')
    j += 1

输出:

check_this
check that
check that

相关问题 更多 >