Understanding inputMenu() from PyInputPlus with Examples

Comprehensive Guide to inputMenu() from PyInputPlus

inputMenu() is a user-friendly function from the PyInputPlus module that allows you to present menu-like options to users. This function is excellent for building interactive command-line interfaces where choices need to be constrained.


πŸ”Ή What is inputMenu()?

inputMenu() displays a list of choices and lets the user select one. The function ensures that only valid options are accepted, reducing the need for manual input validation.


πŸ“Œ Basic Example

This basic example presents a numbered list of programming languages:

import pyinputplus as pyip

lang = pyip.inputMenu(['Python', 'Java', 'C++'], numbered=True)
print(f"Language selected: {lang}")

Explanation: The numbered=True option tells inputMenu() to display the choices with numbers. The user can type either the name or the number.

Note: The inputMenu()has default prompt Please select one of the following:. We will learn how to customise it later in this post

Sample Interaction 1: Choosing Number


Please select one of the following:
1. Python
2. Java
3. C++
java
Language selected: Java

Sample Interaction 2: Choosing Name

Please select one of the following:
1. Python
2. Java
3. C++
Python
Language selected: Python

Note:It is not Case Sensitive So both 'Python' and 'python' have same output

Example:

Please select one of the following:
1. Python
2. Java
3. C++
python
Language selected: python

πŸ“Œ Custom Prompt

import pyinputplus as pyip

lang = pyip.inputMenu(['Python', 'Java', 'C++'], numbered=True,prompt = "Enter Your Choice: \n")
print(f"Language selected: {lang}")

Sample Interaction :


Enter Your Choice:
1. Python
2. Java
3. C++
java
Language selected: Java

πŸ“ Bulleted Menu

If you prefer a bulleted list instead of numbers, use numbered=False:

It cannot Support numbers(1,2...) as Input

import pyinputplus as pyip
food = pyip.inputMenu(['Pizza', 'Burger', 'Pasta'], numbered=False)
print(f"Food chosen: {food}")
Please select one of the following:
* Python
* Java
* C++
Python
Language selected: Python

Explanation: This version shows options with * bullets. The user must type the name exactly unless caseSensitive is adjusted.


β›” Limit Attempts and Provide Default Value

import pyinputplus as pyip

option = pyip.inputMenu(['Yes', 'No'], limit=2, default='No')
print(f"Final decision: {option}")

Explanation: The limit sets how many invalid attempts are allowed. If the user fails to provide a valid response in 2 tries, default='No' is returned automatically.

Sample Interaction:No Correct Input Is Given

Please select one of the following:
* Yes
* No
sorry
'sorry' is not a valid choice.
Please select one of the following:
* Yes
* No
idk
'idk' is not a valid choice.
Final decision: No

Sample Interaction:Correct Input Is Given

Please select one of the following:
* Yes
* No
yes
Final decision: Yes

πŸ”€ Enable Case Sensitivity

Sometimes users may type options in different cases. You can handle this using caseSensitive=False.

import pyinputplus as pyip

choice = pyip.inputMenu(['Red', 'Blue'], caseSensitive=True)
print(f"Color: {choice}")

Explanation: This allows "red", "Red", or "RED" will be treated different.


πŸ“¦ Real-World Example: Mode Selection

import pyinputplus as pyip

mode = pyip.inputMenu(['Basic', 'Advanced', 'Exit'], numbered=True, prompt="Select mode:\n")
print(f"Running in {mode} mode.")

Use Case: Great for terminal-based apps that switch between different functionalities or exit conditions.


🎯 Summary

  • Safe input: Users can only choose valid options.
  • Flexible display: Numbered or bulleted menus.
  • Custom prompts: Easily adjust user instructions.
  • Error handling: Use limit and default for better control.

Using inputMenu() makes your programs more user-friendly and error-resistant. Ideal for interactive Python scripts and beginner projects.

πŸ“š 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

πŸ“– More Resources

πŸ“š Python Crash Course Chapter-wise Exercises
πŸ“š AI And MACHINE LEARNING ROADMAP: From Basic to Advanced
    Stage 1: Python & Programming Fundamentals
    
    ----------------------------------------
    1. Python & Programming Fundamentals
    ----------------------------------------
    1.1 Environment Setup
        β€’ Install Python 3.x, VS Code / PyCharm
        β€’ Configure linting, formatters (e.g., Pylint, Black)
        β€’ Jupyter Notebook / Google Colab basics
    
    1.2 Core Python Syntax
        β€’ Variables, Data Types (int, float, str, bool)
        β€’ Operators: arithmetic, comparison, logical, bitwise
        β€’ Control Flow: if / else / elif
        β€’ Loops: for, while, break/continue
    
    1.3 Functions & Modules
        β€’ Defining functions, return values
        β€’ Parameters: positional, keyword, default args
        β€’ *args, **kwargs
        β€’ Organizing code: modules and packages
        β€’ Standard library exploration (os, sys, datetime, random, math)
    
    1.4 Data Structures
        β€’ Lists, Tuples, Sets, Dictionaries
        β€’ List/dict comprehensions
        β€’ Built-in functions: map, filter, zip, enumerate
        β€’ When to use which structure
    
    1.5 File Handling & Exceptions
        β€’ Reading/Writing text and binary files
        β€’ Context managers (`with` statement)
        β€’ Exception handling: try/except/finally
        β€’ Custom exceptions
    
    1.6 Object-Oriented Programming (OOP)
        β€’ Classes, Instances, Attributes, Methods
        β€’ __init__, self, class vs instance attributes
        β€’ Inheritance, Polymorphism, Encapsulation
        β€’ Magic methods: __str__, __repr__, __add__, etc.
        β€’ Use-cases in structuring larger projects
    
    1.7 Virtual Environments & Package Management
        β€’ venv / pipenv / poetry basics
        β€’ Installing and managing dependencies
        β€’ requirements.txt and environment.yml
    
    πŸ›  Tools: VS Code, Git for version control, Jupyter/Colab
        
    Stage 2: Mathematics for Machine Learning
    
    ----------------------------------------
    2. Mathematics for Machine Learning
    ----------------------------------------
    2.1 Linear Algebra
        β€’ Scalars, Vectors, Matrices, Tensors
        β€’ Operations: addition, multiplication, dot product
        β€’ Matrix properties: transpose, inverse, rank
        β€’ Eigenvalues & Eigenvectors (intuition)
        β€’ Applications: data transformations, PCA
    
    2.2 Calculus
        β€’ Functions and limits (intuitive overview)
        β€’ Derivatives: gradient of single-variable and multi-variable functions
        β€’ Chain rule (key for backpropagation in neural networks)
        β€’ Partial derivatives
        β€’ Basic integration (overview; less often used directly)
    
    2.3 Probability & Statistics
        β€’ Basic probability theory: events, conditional probability, Bayes’ theorem
        β€’ Random variables, distributions (normal, binomial, Poisson, etc.)
        β€’ Descriptive statistics: mean, median, mode, variance, standard deviation
        β€’ Inferential statistics: hypothesis testing, p-values, confidence intervals
        β€’ Sampling methods, bias, variance concepts
    
    2.4 Optimization Basics
        β€’ Concept of optimization in ML (finding minima of loss functions)
        β€’ Gradient descent: batch, stochastic, mini-batch
        β€’ Learning rate intuition
    
    πŸ›  Tools / References: 
        β€’ Interactive calculators: Desmos, GeoGebra
        β€’ Python libraries: NumPy for experimentation
        
    Stage 3: Data Handling & Preprocessing
    
    ----------------------------------------
    3. Data Handling & Preprocessing
    ----------------------------------------
    3.1 NumPy Essentials
        β€’ ndarrays: creation, indexing, slicing
        β€’ Vectorized operations vs Python loops
        β€’ Broadcasting rules
        β€’ Random number generation
    
    3.2 Pandas for Tabular Data
        β€’ Series & DataFrame: creation and basic ops
        β€’ Reading data: CSV, Excel, JSON
        β€’ Indexing, selection (loc/iloc), filtering rows
        β€’ Handling missing values: dropna, fillna
        β€’ Detecting/removing duplicates
        β€’ Combining datasets: merge, join, concat
        β€’ GroupBy operations, aggregation, pivot tables
    
    3.3 Feature Engineering
        β€’ Feature scaling: normalization (Min-Max), standardization (Z-score)
        β€’ Encoding categorical variables: one-hot, ordinal encoding
        β€’ Date/time feature extraction (if applicable)
        β€’ Creating new features via domain knowledge
        β€’ Feature selection: variance threshold, correlation analysis
    
    3.4 Data Visualization
        β€’ Matplotlib basics: line plot, scatter plot, histograms, bar charts
        β€’ Seaborn overview: higher-level plots (heatmap, pairplot)
        β€’ Visualizing distributions, relationships, outliers
        β€’ Plot customization: titles, labels, legends
    
    3.5 Handling Real-World Data Challenges
        β€’ Imbalanced datasets: oversampling (SMOTE), undersampling, class weights
        β€’ Outlier detection and treatment
        β€’ Data leakage awareness
        β€’ Pipeline creation in scikit-learn
    
    πŸ›  Tools: NumPy, Pandas, Matplotlib, Seaborn, scikit-learn utilities
        
    Stage 4: Core Machine Learning
    
    ----------------------------------------
    4. Core Machine Learning
    ----------------------------------------
    4.1 ML Concepts & Workflow
        β€’ What is ML? Supervised vs Unsupervised vs Semi-supervised vs Reinforcement
        β€’ Training, Validation, Testing splits
        β€’ Overfitting vs Underfitting, bias-variance trade-off
        β€’ Cross-validation techniques: k-fold, stratified
    
    4.2 Supervised Learning: Regression
        β€’ Linear Regression: assumptions, cost function, normal equation
        β€’ Regularized Regression: Ridge, Lasso, Elastic Net
        β€’ Polynomial Regression
        β€’ Evaluation metrics: MSE, RMSE, MAE, RΒ²
    
    4.3 Supervised Learning: Classification
        β€’ Logistic Regression: sigmoid, decision boundary, loss
        β€’ k-Nearest Neighbors (KNN)
        β€’ Decision Trees: entropy/gini, pruning
        β€’ Ensemble Methods:
            - Bagging: Random Forest
            - Boosting: AdaBoost, Gradient Boosting, XGBoost (intro)
        β€’ Support Vector Machines (SVM): kernel trick overview
        β€’ Naive Bayes: Gaussian, Multinomial
        β€’ Evaluation: accuracy, precision, recall, F1-score, ROC-AUC
        β€’ Confusion matrix analysis
    
    4.4 Unsupervised Learning
        β€’ Clustering:
            - K-Means: elbow method, silhouette score
            - Hierarchical clustering: dendrograms
            - DBSCAN
        β€’ Dimensionality Reduction:
            - PCA: variance explained
            - t-SNE / UMAP (visualization-focused)
        β€’ Anomaly Detection overview
    
    4.5 Model Selection & Tuning
        β€’ Hyperparameter tuning: grid search, random search, Bayesian optimization (overview)
        β€’ Automated tuning libraries (e.g., scikit-learn’s GridSearchCV, RandomizedSearchCV)
        β€’ Pipeline building to avoid leakage
        β€’ Feature importance and model interpretability basics
    
    πŸ›  Tools: scikit-learn, pandas, NumPy
        
    Stage 5: Deep Learning Foundations
    
    ----------------------------------------
    5. Deep Learning Foundations
    ----------------------------------------
    5.1 Neural Network Basics
        β€’ Artificial neuron model, activation functions (ReLU, Sigmoid, Tanh)
        β€’ Architecture: input, hidden, output layers
        β€’ Forward propagation, loss functions (Cross-entropy, MSE)
        β€’ Backpropagation: gradient computation, chain rule
    
    5.2 Deep Learning Frameworks
        β€’ TensorFlow & Keras: Sequential and Functional APIs
        β€’ PyTorch basics: tensors, autograd, nn.Module
        β€’ Comparing TF/Keras vs PyTorch (choose one to start)
    
    5.3 Training Deep Models
        β€’ Optimizers: SGD, Adam, RMSprop
        β€’ Learning rate scheduling
        β€’ Regularization: Dropout, Batch Normalization, Weight Decay
        β€’ Handling overfitting: early stopping, data augmentation
    
    5.4 Basic DL Projects
        β€’ MNIST digit classification
        β€’ CIFAR-10 image classification (small CNN)
        β€’ Simple feedforward network on tabular data
    
    πŸ›  Tools: TensorFlow/Keras or PyTorch, GPU if available (Colab/GPU runtime)
        
    Stage 6: Advanced Deep Learning & Architectures
    
    ----------------------------------------
    6. Advanced Deep Learning & Architectures
    ----------------------------------------
    6.1 Convolutional Neural Networks (CNNs)
        β€’ Convolution operations, filters, feature maps
        β€’ Pooling layers, padding, stride
        β€’ Famous architectures overview: LeNet, AlexNet, VGG, ResNet (intuition)
        β€’ Transfer Learning: fine-tuning pre-trained models
    
    6.2 Recurrent Neural Networks (RNNs) & Sequence Models
        β€’ RNN basics: hidden states, vanishing gradients
        β€’ LSTM, GRU: gating mechanisms
        β€’ Sequence-to-sequence models (intro)
        β€’ Attention mechanism: intuition
    
    6.3 Transformers & Attention
        β€’ Self-attention mechanism
        β€’ Transformer architecture: encoder, decoder overview
        β€’ Pre-trained transformer models: BERT, GPT family (conceptual)
        β€’ Fine-tuning transformers for tasks
    
    6.4 Generative Models
        β€’ Autoencoders: basic, variational autoencoders (VAE) overview
        β€’ Generative Adversarial Networks (GANs): generator/discriminator intuition
        β€’ Applications and basic experiments
    
    6.5 Advanced Techniques
        β€’ Multi-task learning, meta-learning (intro)
        β€’ Few-shot learning, transfer learning deeper dive
        β€’ Neural architecture search (overview)
        β€’ Model compression, pruning, quantization (deployment considerations)
    
    πŸ›  Tools: TensorFlow / PyTorch, Hugging Face Transformers library
        
    Stage 7: Natural Language Processing (NLP) Advanced
    
    ----------------------------------------
    7. Natural Language Processing (NLP)
    ----------------------------------------
    7.1 Text Preprocessing & Representation
        β€’ Tokenization (word, subword/BPE)
        β€’ Stopwords removal, lemmatization vs stemming
        β€’ Word embeddings: Word2Vec, GloVe, FastText
        β€’ Contextual embeddings: ELMo, BERT embeddings
    
    7.2 Transformer-based NLP
        β€’ Pre-trained models: BERT, RoBERTa, GPT, T5
        β€’ Fine-tuning for classification, QA, summarization
        β€’ Sequence generation tasks using GPT-like models
    
    7.3 Specialized NLP Tasks
        β€’ Named Entity Recognition (NER)
        β€’ Machine Translation overview
        β€’ Question Answering pipelines
        β€’ Text Summarization (extractive vs abstractive)
        β€’ Sentiment Analysis deep dive
    
    7.4 Evaluation Metrics in NLP
        β€’ BLEU, ROUGE, METEOR (for generation)
        β€’ Accuracy, F1 for classification tasks
    
    πŸ›  Tools: Hugging Face Transformers, spaCy, NLTK
        
    Stage 8: Computer Vision Advanced
    
    ----------------------------------------
    8. Computer Vision (CV)
    ----------------------------------------
    8.1 Image Preprocessing & Augmentation
        β€’ OpenCV basics: reading, resizing, color conversions
        β€’ Data augmentation techniques: flips, rotations, crops, color jitter
    
    8.2 Advanced CNN Architectures
        β€’ Inception, ResNet, DenseNet, EfficientNet (conceptual)
        β€’ Transfer learning and fine-tuning advanced models
        β€’ Object detection frameworks: YOLOvX, SSD, Faster R-CNN (overview)
        β€’ Semantic segmentation: U-Net, Mask R-CNN
        β€’ Instance segmentation concepts
    
    8.3 Vision Transformers (ViT)
        β€’ Applying transformer concepts to images
        β€’ Fine-tuning ViT for classification
    
    8.4 Specialized CV Tasks
        β€’ Face recognition pipelines
        β€’ Video analysis basics: action recognition, object tracking
        β€’ 3D vision intro (depth estimation)
    
    πŸ›  Tools: OpenCV, TensorFlow/PyTorch, libraries like Detectron2 or YOLO implementations
        
    Stage 9: Reinforcement Learning & Advanced Topics
    
    ----------------------------------------
    9. Reinforcement Learning & Advanced Topics
    ----------------------------------------
    9.1 Reinforcement Learning Foundations
        β€’ Markov Decision Process (MDP)
        β€’ Value functions, policy functions
        β€’ Q-Learning, SARSA (tabular methods)
        β€’ Exploration vs Exploitation
    
    9.2 Deep Reinforcement Learning
        β€’ Deep Q-Networks (DQN)
        β€’ Policy Gradient Methods: REINFORCE, Actor-Critic
        β€’ Advanced: A3C, PPO, DDPG overview
    
    9.3 Other Advanced AI Topics
        β€’ Graph Neural Networks (GNNs): node/graph embeddings (overview)
        β€’ Time Series Forecasting with ML/DL: RNN/LSTM, Prophet intro
        β€’ Bayesian Methods overview
        β€’ AutoML and neural architecture search concepts
        β€’ Federated Learning basics (privacy-aware training)
        β€’ MLOps fundamentals:
            - Model versioning
            - Continuous integration/continuous deployment (CI/CD) for ML
            - Monitoring models in production
            - Tools: MLflow, Kubeflow (intro)
        β€’ Edge AI / TinyML overview (deploying models on devices)
    
    πŸ›  Tools: RL libraries (Stable Baselines3), MLflow, Kubernetes intro, Docker
        
    Stage 10: Deployment, Production & MLOps
    
    ----------------------------------------
    10. Deployment, Production & MLOps
    ----------------------------------------
    10.1 Model Serving & APIs
        β€’ REST API with Flask / FastAPI
        β€’ gRPC basics (overview)
        β€’ Dockerizing ML applications
        β€’ Serving with TensorFlow Serving or TorchServe
    
    10.2 Cloud Deployment
        β€’ Deploy on AWS Sagemaker / GCP AI Platform / Azure ML (basic workflow)
        β€’ Serverless deployments (AWS Lambda, Cloud Functions) for small models
        β€’ CI/CD pipelines for ML: GitHub Actions or Jenkins integration
    
    10.3 Monitoring & Maintenance
        β€’ Logging model inputs/outputs
        β€’ Drift detection (data/model drift)
        β€’ Retraining pipelines (automated or scheduled)
        β€’ Scaling considerations
    
    10.4 MLOps Tools & Practices
        β€’ Experiment tracking (MLflow, Weights & Biases)
        β€’ Data versioning (DVC)
        β€’ Model registry concepts
        β€’ Infrastructure as Code (Terraform intro)
    
    πŸ›  Tools: Docker, Kubernetes basics, CI/CD tools, cloud consoles
        
    Stage 11: Real-World Projects & Portfolio
    
    ----------------------------------------
    11. Real-World Projects & Portfolio
    ----------------------------------------
    11.1 Project Ideas by Domain
        β€’ Tabular Data: Predictive analytics (e.g., churn prediction)
        β€’ NLP: Chatbot, summarizer, translation prototype
        β€’ CV: Image classifier, object detector, image segmentation app
        β€’ Time Series: Forecasting stock or weather data
        β€’ RL: Simple game-playing agent
        β€’ Generative: GAN art generation or style transfer demo
    
    11.2 End-to-End Pipeline
        β€’ Data collection & preprocessing
        β€’ Model training & validation
        β€’ Deployment as API or web app (Streamlit/Flask)
        β€’ Monitoring & iteration
        β€’ Documentation & README
    
    11.3 Collaboration & Open Source
        β€’ Participate in Kaggle competitions (beginner β†’ intermediate)
        β€’ Contribute to open-source ML projects
        β€’ Write blog posts/tutorials documenting your projects
    
    11.4 Soft Skills & Communication
        β€’ Clear README, code comments
        β€’ Presentation slides or videos of project demos
        β€’ Networking: sharing work on LinkedIn, GitHub
    
    πŸ›  Tools: GitHub Pages, Streamlit, Heroku/Netlify, Docker
        
    Stage 12: Ethics, Explainability & Continuous Learning
    
    ----------------------------------------
    12. Ethics, Explainability & Continuous Learning
    ----------------------------------------
    12.1 AI Ethics & Responsible AI
        β€’ Bias & Fairness: identifying and mitigating bias
        β€’ Privacy concerns: GDPR, data protection best practices
        β€’ Transparency: documenting data sources and model decisions
    
    12.2 Explainable AI (XAI)
        β€’ Model interpretability: SHAP, LIME (basic usage)
        β€’ Interpreting black-box models vs inherently interpretable models
        β€’ Communicating explanations to stakeholders
    
    12.3 Continuous Learning & Staying Updated
        β€’ Following research: arXiv alerts, ML conferences (NeurIPS, ICML, CVPR summaries)
        β€’ Blogs, podcasts, newsletters (e.g., β€œThe Batch” by deeplearning.ai)
        β€’ Reading codebases of popular libraries, exploring new architectures
        β€’ Community involvement: forums, study groups
    
    12.4 Advanced Research Topics (Optional/For Aspirants)
        β€’ Research paper reading workflow
        β€’ Experimentation frameworks
        β€’ Contributing to academic research or advanced industrial research
    
    πŸ›  Tools: arXiv, Google Scholar alerts, RSS readers, community forums
        

Comments