Home > Enterprise >  why While loop keep moves to below statement even though it becomes true?
why While loop keep moves to below statement even though it becomes true?

Time:01-19

I have come up with the below line of code to solve: Using while loop keep asking for user input till user come up with the number in range(1,11).

My question is when I put 123 as input, my while loop still works. Why? Shouldn't it quit since user_input.isdigit() becomes True for 123 as input?

def userinput():
    
    user_input = 'wrong'   

    while user_input.isdigit() == False:
        
        while user_input not in range(1,11):
            
            user_input = input('What no. are you proposing in range(1,10)?  :')

            if user_input.isdigit() == False or int(user_input) not in range(1,11):

                print(f'Please try again\n')

            else:
                print('You have guessed correctly!')
                break

    return int(user_input)

CodePudding user response:

Your inner loop condition is not met so your outer loop condition is not checked.

CodePudding user response:

@khelwood i'm not asking for answer. Read first, before downvoting.I came up with own solution. Here, I am just asking for my future knowledge.Thats all!

CodePudding user response:

try this:

def userinput():
    
    user_input = 'wrong'   

    while True:
            
        user_input = input('What no. are you proposing in range(1,10)?  :')
        if user_input.isdigit() == False or int(user_input) not in range(1,11):
            print(f'Please try again\n')
        else:
            print('You have guessed correctly!')
            break

    return int(user_input)

CodePudding user response:

Consider this simpler alternative.

def userinput():
    user_input = 0
    while user_input not in range(1, 11):
        user_input = input('What no. are you proposing in range(1,10)?  :')
        if user_input.isdigit() and int(user_input) in range(1, 11):
            print('You have guessed correctly!')
            break
        else:
            print(f'Please try again\n')
    return int(user_input)
  •  Tags:  
  • Related