Understanding inputChoice() from PyInputPlus with Examples

Complete Guide to inputChoice() in PyInputPlus

The inputChoice() function from PyInputPlus allows users to select from a predefined list of choices. It simplifies validation by ensuring input matches one of the allowed items.


πŸ”Ή Basic Usage

This example prompts the user to select one of the predefined items. If the input doesn't match, it will prompt again.

import pyinputplus as pyip

choice = pyip.inputChoice(['dog', 'cat', 'bird'])
print(f"You selected: {choice}")

What It Does:

  • Asks user to enter "dog", "cat", or "bird".
  • Rejects any other input.
  • Note: It has a default prompt like Please select one of: dog, cat, bird
  • Note: numbered is not supported in inputChoice()

Sample Output:

Please select one of: dog, cat, bird
moon
'moon' is not a valid choice.
Please select one of: dog, cat, bird
dog
You selected: dog

πŸ”Ή Custom Prompt

fruit = pyip.inputChoice(['apple', 'banana'], prompt="Pick your favorite fruit: ")
print(f"Chosen fruit: {fruit}")

What It Does:

  • Changes default prompt text.

Sample Output:

Pick your favorite fruit: banana
Chosen fruit: banana

πŸ”Ή Limit Attempts + Default Fallback

food = pyip.inputChoice(['pizza', 'burger'], limit=2, default='pizza')
print(f"Food selected: {food}")

What It Does:

  • User has 2 attempts to enter valid input.
  • If both fail, "pizza" (default) is returned.

Sample Output:

Please select one of: pizza, burger
hotdog
'hotdog' is not a valid choice.
Please select one of: pizza, burger
samosa
'samosa' is not a valid choice.
Food selected: pizza

πŸ”Ή Real-world Scenario: Confirm Action

confirm = pyip.inputChoice(['yes', 'no'], prompt="Are you sure you want to delete? (yes/no): ")
if confirm == 'yes':
    print("Deleted.")
else:
    print("Action canceled.")

Use Case:

  • Useful for confirmations before critical operations.

Conclusion: inputChoice() is a powerful and safe way to capture predefined responses, enhancing user experience and input validation.

πŸ“š Related Topics from PyInputPlus:


“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python

πŸ“Œ Follow Us And Stay Updated For Daily Updates

Comments