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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With