Skip to content

Instantly share code, notes, and snippets.

@Kqzz
Created August 6, 2020 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kqzz/dc1846ef7d997d03fb8058a16a67c79e to your computer and use it in GitHub Desktop.
Save Kqzz/dc1846ef7d997d03fb8058a16a67c79e to your computer and use it in GitHub Desktop.
A very simple python function to ask which option to select from a given list of options
# For this to work you need to run "pip install readchar" for this script to work.
# Also, if you are using this in a project add readchar to your requirements.txt file
import readchar
def ask_option(options):
i = 1
# loop through options and print
for option in options:
print(f"{i}). {option}")
i += 1
# main function loop
# Doesn't end until a correct answer is given
while True:
try:
# takes an input using readchar's readkey function
choice = int(readchar.readkey())
selection_validation = options[choice - 1]
# returns the option the user selected by list index
# example: the user selected option 3 and it will return 2 which is the list index of the selected element
return choice - 1
except (ValueError, IndexError):
print("please enter a valid option")
# Runs only if the file is being run directly rather than being imported as a module
if __name__ == '__main__':
# run ask_option and pass a list
ask_option(["option 1", "option 2", "option 3", "option 4", ])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment