Search code examples
pythonloopswhile-loopnested-loopsexit

Python: Multiple controlled while loops inside while loop


Please help me to solve this issue! Python 3 code:

x=True
while x:
     a=input('Enter an num:')
     y=a.isdigit()
     while y:
         b=input('Enter an alphabet:')
         z=b.isalpha
         while z:
             print('This is a nested while loop')
             z=False
             y=False
             x=False
             break
        else:
             print('wrong alphabet, Please try again !')
    else:
        print('wrong num format, Please try again !')

when I run this code and enter: Enter a num:123 Enter an alphabet: dog This is a nested while loop wrong num format, Please try again!

I don't want to print the wrong num format text. I also used exit to control the loop but not helpful. Please suggest me better ans.


Solution

  • In evaluating your code I did some simplification to the code along with changing out some of the "while" statements with "if" statements. Following is a revised code snippet.

    while True:
        a=input('Enter an number: ')
        if a.isdigit():     # Instead of storing a boolean value, plus it works with the else statement below
            while True:
                b=input('Enter an alphabetic character: ')
                if b.isalpha():
                    print('This is a nested while loop - goodbye')
                    quit()      # Instead of breaking out of multiple while loops
                else:
                    print('Wrong alphabet, Please try again !')
        else:
            print('Wrong number format, Please try again !')
    

    Here are some points to note.

    • Even though the result of a alphabetic or numeric test can be stored in a Boolean variable, often times it is easier and more evident to utilize the constants "True" or "False" or use the function test directly in the test statement. This usually cuts down on the lines of code needed.
    • The "else" clause is meant to be utilized with an "if" test and not a "while" loop. So with that in mind, certain "while" loops were revised to be "if" tests to match up with the "else" clause.
    • Instead of trying to break out of multiple "while" loops when the end goal is to exit the program, a simpler approach is to either utilize the "sys.exit()" operation or the "quit()" operation if module sys has not been imported.

    Testing that out, following is some sample terminal output.

    @Dev:~/Python_Programs/Nested$ python3 Nested.py 
    Enter an number: e
    Wrong number format, Please try again !
    Enter an number: 3445
    Enter an alphabetic character: w3e
    Wrong alphabet, Please try again !
    Enter an alphabetic character: Hello
    This is a nested while loop - goodbye
    

    Give that a try to see if that meets the spirit of your project.