Search code examples
pythonuser-input

This is about validating user input, i was doing a tutorial and didnt understand why he had defined the below


Below is the code. What i dont understand is in the Initial part he defined 3 things. choice, acceptable_range and within_range.

why did he have to define within_range?

def user_choice():
    
    #Variables
    
    # Initial 
    choice ='thiscanbeanything'
    acceptable_range = range(0,10)
    within_range = False 
    
    #Two condition to check 
    #Digit or within range = False 
    
    
    
    while choice.isdigit() == False or within_range==False: 
    
    
        choice = input("Please enter a number (0-10): ")
        
        #Digit check
        if choice.isdigit() == False:
            print("sorry that is not a digit!")
    
        #Range check
        if choice.isdigit() == True: 
            if int(choice) in acceptable_range:
                within_range = True 
            else:
                print("sorry, you are out of acceptable range")
                within_range = False 
    
    return int(choice)

Solution

  • If within_range wasn't defined, you would never enter in the while loop, you need to define it to false first to enter in the loop. Once you're in the loop, this value is defined depending of the choice value (with the input function)