Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command line: Show list of options and let user choose [closed]

Tags:

python

Assuming I have a list of options:

options = ["Option 1", "Option 2", "Option 3"]

And I would like the user to choose an option on the command line, e.g. something like this:

Please choose:
1) Option 1
2) Option 2
3) Option 3
Enter number: <user input>

So I am looking for the implementation of the following:

choice = let_user_pick(options) # returns integer

How would one go about this in python?

like image 271
ig-dev Avatar asked Dec 02 '25 22:12

ig-dev


1 Answers

def let_user_pick(options):
    print("Please choose:")
    for idx, element in enumerate(options):
        print("{}) {}".format(idx+1,element))
    i = input("Enter number: ")
    try:
        if 0 < int(i) <= len(options):
            return int(i)
    except:
        pass
    return None

You might want to instead return int(i)-1 in order to use the result as an index of your options list, or return the option directly. It might also be good to instead of returning None loop over the whole thing until the user enters a correct choice.

like image 59
L3viathan Avatar answered Dec 05 '25 13:12

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!