Search code examples
pythoninputintegeruser-inputstring-length

How to restrict the choice of a user in python?


So I have this program where I need the user to choose a length for a key in python but I want the choice of the user to be restricted with the provided lengths only and I don't quite know how to do that here is the code

available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
length = int(input("[+]:Select the length you want for your key: "))

I want to make so that if the user inputs a length not available in the list to print "Please choose a valid length" and take him back to input the length

I have tried:

 while True:
        length = int(input("[+]:Select the length you want for your key: "))
        if 5 <= length <= 21:
            break

Solution

  • You can't control what the user inputs. You can control whether or not you ask for a different input.

    Model this with an infinite loop and an explicit break statement.

    available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
    while True:
        length = int(input("[+]:Select the length you want for your key: "))
        if length in availble_len:
            break
    

    While you can shorten this using an assignment expression, I find this approach to be clearer.

    available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
    while (length := int(input("[+]:Select the length you want for your key: "))) not in available_len:
        pass
    

    You could replace pass with a print statement explaining why the previous choice was invalid.