Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading