PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to restrict the choice of a user in python?

 July 20, 2022     input, integer, python, string-length, user-input     No comments   

Issue

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.



Answered By - chepner
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing