0

As I am a new learner in python, I was trying to do an exercise having while loop in it. I have written a piece of code which will ask user to enter his details. After getting all the details the program should stop, but In my case after entering Account Number, it again start asking Mobile number to enter.

Please have a look at the code and suggest where I am going wrong.

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!!")
Vishal Mishr
  • 195
  • 1
  • 8
  • Do you expect the `break` to exit from the external loop? It should break the internal one... – Elyash Oct 06 '20 at 11:25
  • your `break` on line 15 exits only for `while (True):` which the scope is. Add some flags to exit for two loops. – Joona Yoon Oct 06 '20 at 11:31

1 Answers1

2

The break statement inside the inner loop will break the inner loop but not the outer. You should re-think the logic and maybe add bool variable to check if inner loop broke so you can break the outer loop. For/while loops have else statements which will check if the loop called finished successfully or was aborted with a break. In the case of a while loop, the else will be executed if the condition in the is no longer true. Take a look at: https://book.pythontips.com/en/latest/for_-_else.html

To give you an example:

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

Output:

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

Now change the bank to 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

Output:

check_this
check that
check that
picatostas
  • 58
  • 8