💬 Getting User Input
Getting user input allows your Python programs to interact with users, creating dynamic and responsive applications. Using the input()
function and validation techniques, you can build programs that adapt to user needs and provide personalized experiences.
Think of user input as the conversation between your program and its users - it's how your application listens, understands, and responds to what people want to accomplish.
# Simple input collection
def basic_input_demo():
"""Demonstrate basic input collection"""
print("=== Basic Input Demo ===")
# Simulate user input for demonstration
sample_inputs = ["Alice Johnson", "28", "blue"]
input_prompts = ["What's your name? ", "How old are you? ", "What's your favorite color? "]
for prompt, user_input in zip(input_prompts, sample_inputs):
print(f"{prompt}{user_input}")
if "name" in prompt.lower():
print(f"Hello, {user_input}! Nice to meet you.")
elif "age" in prompt.lower():
try:
age = int(user_input)
print(f"In 10 years, you'll be {age + 10} years old")
except ValueError:
print("Please enter a valid age!")
elif "color" in prompt.lower():
print(f"Great choice! {user_input} is a beautiful color.")
print()
basic_input_demo()
🎯 Understanding Input Handling
User input handling involves collecting, validating, and converting data while providing clear feedback and error recovery.
Input Validation Patterns
Different input scenarios require specific approaches for optimal user experience and data validation.
def get_validated_input(prompt, validator_func, error_message="Invalid input"):
"""Generic input validation function"""
while True:
try:
user_input = input(prompt).strip()
if validator_func(user_input):
return user_input
else:
print(error_message)
except KeyboardInterrupt:
print("\nOperation cancelled by user")
return None
except Exception as e:
print(f"Unexpected error: {e}")
def validate_name(name):
"""Validate name input"""
return len(name) >= 2 and not name.isdigit()
def validate_email(email):
"""Validate email format"""
return "@" in email and "." in email and len(email) > 5
def validate_age(age_str):
"""Validate age input"""
try:
age = int(age_str)
return 0 <= age <= 150
except ValueError:
return False
# Demonstrate validation patterns (simulated)
def input_validation_demo():
"""Show input validation in action"""
print("=== Input Validation Demo ===")
# Simulate different validation scenarios
test_cases = [
("Alice Johnson", validate_name, "Valid name"),
("A", validate_name, "Name too short"),
("123", validate_name, "Numbers not allowed"),
("alice@example.com", validate_email, "Valid email"),
("invalid-email", validate_email, "Invalid email format"),
("25", validate_age, "Valid age"),
("200", validate_age, "Age out of range"),
("abc", validate_age, "Age not a number")
]
for test_input, validator, description in test_cases:
is_valid = validator(test_input)
status = "✅" if is_valid else "❌"
print(f"{status} '{test_input}' - {description}")
input_validation_demo()
⚡ Advanced Input Handling
Numeric Input with Range Validation
Numeric validation ensures mathematical operations work correctly and prevents calculation errors.
def get_integer_input(prompt, min_value=None, max_value=None):
"""Get validated integer input with optional range checking"""
while True:
try:
# Simulate user input for demo
print(f"{prompt}", end="")
# Test different scenarios
test_values = ["25", "abc", "150", "-5", "75"]
for test_value in test_values:
print(f"{test_value}")
try:
value = int(test_value)
if min_value is not None and value < min_value:
print(f"❌ Value must be at least {min_value}")
continue
if max_value is not None and value > max_value:
print(f"❌ Value must be no more than {max_value}")
continue
print(f"✅ Valid input: {value}")
return value
except ValueError:
print("❌ Please enter a valid whole number.")
continue
except KeyboardInterrupt:
print("\nOperation cancelled")
return None
def get_float_input(prompt, min_value=None, max_value=None):
"""Get validated decimal number input"""
print(f"\n=== Float Input Demo ===")
test_values = ["3.14", "abc", "10.5", "-2.5", "8.75"]
for test_value in test_values:
print(f"{prompt}{test_value}")
try:
value = float(test_value)
if min_value is not None and value < min_value:
print(f"❌ Value must be at least {min_value}")
continue
if max_value is not None and value > max_value:
print(f"❌ Value must be no more than {max_value}")
continue
print(f"✅ Valid decimal: {value}")
break
except ValueError:
print("❌ Please enter a valid number (e.g., 3.14).")
# Demonstrate numeric input validation
print("=== Integer Input Demo ===")
age = get_integer_input("Enter your age (0-120): ", min_value=0, max_value=120)
get_float_input("Enter price ($0.00-$100.00): ", min_value=0.0, max_value=100.0)
Choice Selection and Menus
Menu systems provide structured ways for users to select from predefined options.
def get_choice_input(prompt, choices, case_sensitive=False):
"""Get user choice from predefined options"""
if not case_sensitive:
choices = [choice.lower() for choice in choices]
choice_str = " / ".join(choices)
full_prompt = f"{prompt} ({choice_str}): "
while True:
# Simulate user choices for demo
test_inputs = ["yes", "maybe", "no", "y", "invalid"]
for test_input in test_inputs:
print(f"{full_prompt}{test_input}")
user_choice = test_input.strip()
if not case_sensitive:
user_choice = user_choice.lower()
if user_choice in choices:
print(f"✅ Selected: {user_choice}")
return user_choice
else:
print(f"❌ Invalid choice. Please choose from: {choice_str}")
continue
def create_menu(title, options):
"""Create interactive menu system"""
print(f"\n=== {title} ===")
for i, option in enumerate(options, 1):
print(f"{i}. {option}")
while True:
# Simulate menu selections
test_selections = ["1", "5", "abc", "2", "3"]
for selection in test_selections:
print(f"Select option (1-{len(options)}): {selection}")
try:
choice = int(selection)
if 1 <= choice <= len(options):
selected_option = options[choice - 1]
print(f"✅ You selected: {selected_option}")
return choice, selected_option
else:
print(f"❌ Please enter a number between 1 and {len(options)}")
except ValueError:
print("❌ Please enter a valid number")
# Demonstrate choice input
print("=== Choice Input Demo ===")
choice = get_choice_input("Do you want to continue?", ["yes", "no", "maybe"])
# Demonstrate menu system
menu_options = ["Create new file", "Open existing file", "Save file", "Exit"]
selection, option = create_menu("File Menu", menu_options)
🚀 Interactive Applications
Building Conversational Interfaces
Create engaging user experiences with natural conversation flows and helpful feedback.
class InteractiveApp:
"""Interactive application with conversation flow"""
def __init__(self):
self.user_data = {}
self.conversation_log = []
def greet_user(self):
"""Welcome user and start conversation"""
print("🎉 Welcome to the Interactive Python App!")
print("I'll help you create a personalized profile.")
self.log_interaction("app_start", "User started application")
def collect_user_info(self):
"""Collect user information with validation"""
# Simulate conversation flow
questions = [
("name", "What's your name?", str),
("age", "What's your age?", int),
("email", "What's your email address?", str),
("interests", "What are your interests? (comma-separated)", list)
]
# Simulate user responses
sample_responses = {
"name": "Alice Johnson",
"age": "28",
"email": "alice@example.com",
"interests": "programming, reading, hiking"
}
for field, question, data_type in questions:
print(f"\n{question}")
response = sample_responses.get(field, "")
print(f"> {response}")
try:
if data_type == int:
value = int(response)
if not 0 <= value <= 150:
raise ValueError("Age must be between 0 and 150")
elif data_type == list:
value = [item.strip() for item in response.split(",")]
elif field == "email":
if "@" not in response or "." not in response:
raise ValueError("Invalid email format")
value = response
else:
value = response
self.user_data[field] = value
self.log_interaction(f"collected_{field}", f"Collected {field}: {value}")
print(f"✅ Thanks! Recorded your {field}.")
except ValueError as e:
print(f"❌ Error: {e}")
self.log_interaction(f"error_{field}", str(e))
def show_summary(self):
"""Display user profile summary"""
print("\n🎯 Your Profile Summary:")
print("=" * 30)
for field, value in self.user_data.items():
if field == "interests":
formatted_value = ", ".join(value)
else:
formatted_value = value
print(f"{field.title()}: {formatted_value}")
def log_interaction(self, action, details):
"""Log user interactions for analytics"""
import datetime
self.conversation_log.append({
"timestamp": datetime.datetime.now().isoformat(),
"action": action,
"details": details
})
def get_feedback(self):
"""Collect user feedback"""
print("\n💬 How was your experience?")
feedback_options = ["excellent", "good", "okay", "poor"]
# Simulate feedback
feedback = "good"
print(f"Rate your experience ({'/'.join(feedback_options)}): {feedback}")
if feedback in feedback_options:
self.user_data["feedback"] = feedback
self.log_interaction("feedback", f"User rated experience: {feedback}")
print(f"✅ Thank you for the {feedback} rating!")
# Optional comment
comment = "The app was easy to use and helpful!"
print(f"Any additional comments? {comment}")
if comment:
self.user_data["comment"] = comment
self.log_interaction("comment", f"User comment: {comment}")
def run_app(self):
"""Main application flow"""
try:
self.greet_user()
self.collect_user_info()
self.show_summary()
self.get_feedback()
print("\n🎉 Thank you for using our app!")
print("Your information has been saved securely.")
except KeyboardInterrupt:
print("\n\n👋 Thanks for trying our app! Come back anytime.")
self.log_interaction("app_exit", "User cancelled application")
except Exception as e:
print(f"\n❌ An unexpected error occurred: {e}")
self.log_interaction("error", f"Unexpected error: {e}")
# Run the interactive application
app = InteractiveApp()
app.run_app()
Command-Line Interface Patterns
Professional command-line interfaces provide powerful user interaction capabilities.
def create_cli_calculator():
"""Command-line calculator with user input"""
print("🧮 Python Calculator")
print("=" * 20)
print("Operations: +, -, *, /, **, sqrt")
print("Type 'quit' to exit")
# Simulate calculator session
commands = [
"10 + 5",
"20 * 3",
"100 / 4",
"invalid command",
"sqrt 16",
"quit"
]
for command in commands:
print(f"\n> {command}")
if command.lower() == 'quit':
print("👋 Thanks for using the calculator!")
break
try:
# Parse command
if command.startswith('sqrt'):
parts = command.split()
if len(parts) == 2:
number = float(parts[1])
result = number ** 0.5
print(f"✅ √{number} = {result}")
else:
print("❌ Usage: sqrt <number>")
else:
# Basic arithmetic
if any(op in command for op in ['+', '-', '*', '/', '**']):
# Safe evaluation (in real apps, use proper parsing)
result = eval(command)
print(f"✅ {command} = {result}")
else:
print("❌ Invalid command. Use: number operator number")
except ZeroDivisionError:
print("❌ Error: Cannot divide by zero")
except ValueError:
print("❌ Error: Invalid number format")
except Exception as e:
print(f"❌ Error: {e}")
create_cli_calculator()
🌟 Best Practices and Patterns
Input Sanitization and Security
Proper input handling prevents security vulnerabilities and data corruption.
import re
def sanitize_input(user_input, input_type="text"):
"""Sanitize user input for security and data integrity"""
if not isinstance(user_input, str):
user_input = str(user_input)
# Basic sanitization
sanitized = user_input.strip()
if input_type == "text":
# Remove potentially dangerous characters
sanitized = re.sub(r'[<>\'\"&]', '', sanitized)
# Limit length
sanitized = sanitized[:1000]
elif input_type == "number":
# Allow only digits, decimal point, and minus sign
sanitized = re.sub(r'[^0-9.-]', '', sanitized)
elif input_type == "email":
# Basic email character filtering
sanitized = re.sub(r'[^a-zA-Z0-9@._-]', '', sanitized)
sanitized = sanitized.lower()
elif input_type == "filename":
# Safe filename characters only
sanitized = re.sub(r'[^a-zA-Z0-9._-]', '_', sanitized)
sanitized = sanitized[:255] # Filename length limit
return sanitized
def demonstrate_input_sanitization():
"""Show input sanitization in action"""
test_inputs = [
("Alice<script>alert('xss')</script>", "text"),
("user@example.com", "email"),
("invalid@<script>", "email"),
("123.45abc", "number"),
("my file name!@#.txt", "filename")
]
print("=== Input Sanitization Demo ===")
for original, input_type in test_inputs:
sanitized = sanitize_input(original, input_type)
print(f"Type: {input_type}")
print(f"Original: '{original}'")
print(f"Sanitized: '{sanitized}'")
print()
demonstrate_input_sanitization()
Essential Input Functions and Validation
Understanding core input techniques enables robust user interaction and data collection in Python applications.
Function | Purpose | Example | Best Practice |
---|---|---|---|
input(prompt) | Get user text input | name = input("Enter name: ") | Always provide clear prompts |
int(input()) | Get integer input | age = int(input("Age: ")) | Use try/except for conversion |
float(input()) | Get decimal input | price = float(input("Price: ")) | Validate numeric ranges |
input().strip() | Remove whitespace | text = input("Text: ").strip() | Clean input before processing |
input().lower() | Normalize case | choice = input("Y/N: ").lower() | Consistent comparison |
while True: loop | Input validation | Retry until valid input | Provide clear error messages |
try/except | Handle conversion errors | Catch ValueError exceptions | Graceful error handling |
len(input_text) | Validate input length | Check minimum/maximum length | Prevent empty/long input |
Hands-on Exercise
Create a simple quiz game that asks the user questions and keeps score. Get user input for answers, validate responses, and provide feedback. Include at least 3 questions with different answer types.
def create_quiz_game():
# TODO: Initialize score
# TODO: Create list of questions with answers
# TODO: Loop through questions
# TODO: Get user input for each question
# TODO: Check answers and update score
# TODO: Show final results
pass
def ask_question(question, correct_answer, question_type="text"):
# TODO: Display question
# TODO: Get user input
# TODO: Validate answer based on type
# TODO: Return True if correct, False if wrong
pass
# TODO: Test your quiz game
print("Welcome to the Python Quiz!")
print("Answer the following questions:")
# Sample questions
questions = [
{"question": "What is 5 + 3?", "answer": "8", "type": "number"},
{"question": "What is the capital of France?", "answer": "paris", "type": "text"},
{"question": "Is Python a programming language? (yes/no)", "answer": "yes", "type": "text"}
]
# Run the quiz
create_quiz_game()
Solution and Explanation 💡
Click to see the complete solution
def create_quiz_game():
# Initialize score
score = 0
total_questions = 0
# Create list of questions with answers
questions = [
{"question": "What is 5 + 3?", "answer": "8", "type": "number"},
{"question": "What is the capital of France?", "answer": "paris", "type": "text"},
{"question": "Is Python a programming language? (yes/no)", "answer": "yes", "type": "text"},
{"question": "What is 10 - 4?", "answer": "6", "type": "number"},
{"question": "What color do you get when you mix red and blue?", "answer": "purple", "type": "text"}
]
print("Welcome to the Python Quiz!")
print("Answer the following questions:")
print("-" * 30)
# Loop through questions
for i, q in enumerate(questions, 1):
print(f"\nQuestion {i}:")
if ask_question(q["question"], q["answer"], q["type"]):
score += 1
print("✅ Correct!")
else:
print(f"❌ Wrong! The correct answer is: {q['answer']}")
total_questions += 1
# Show final results
print(f"\n🎯 Quiz Complete!")
print(f"Your score: {score}/{total_questions}")
percentage = (score / total_questions) * 100
print(f"Percentage: {percentage:.1f}%")
if percentage >= 80:
print("🎉 Excellent work!")
elif percentage >= 60:
print("👍 Good job!")
else:
print("📚 Keep studying!")
def ask_question(question, correct_answer, question_type="text"):
# Display question
user_answer = input(f"{question} ")
# Validate answer based on type
if question_type == "number":
try:
# Convert both to numbers for comparison
user_num = float(user_answer)
correct_num = float(correct_answer)
return user_num == correct_num
except ValueError:
return False
else:
# Text comparison (case insensitive)
return user_answer.lower().strip() == correct_answer.lower().strip()
# Test your quiz game (simulation without actual input)
def simulate_quiz():
# Simulate user answers for demonstration
questions = [
{"question": "What is 5 + 3?", "answer": "8", "type": "number"},
{"question": "What is the capital of France?", "answer": "paris", "type": "text"},
{"question": "Is Python a programming language? (yes/no)", "answer": "yes", "type": "text"}
]
# Simulated answers
simulated_answers = ["8", "Paris", "yes"]
print("Quiz Simulation:")
score = 0
for i, q in enumerate(questions):
print(f"\nQuestion {i+1}: {q['question']}")
print(f"Your answer: {simulated_answers[i]}")
# Check answer
if q["type"] == "number":
correct = simulated_answers[i] == q["answer"]
else:
correct = simulated_answers[i].lower() == q["answer"].lower()
if correct:
score += 1
print("✅ Correct!")
else:
print(f"❌ Wrong! Correct answer: {q['answer']}")
print(f"\nFinal Score: {score}/{len(questions)}")
# Run simulation
simulate_quiz()
# Uncomment to run actual interactive quiz:
# create_quiz_game()
Key Learning Points:
- 📌 input() function: Gets text input from the user
- 📌 Input validation: Check answer types and formats before processing
- 📌 String methods: Use .lower() and .strip() for flexible text comparison
- 📌 Score tracking: Keep count of correct answers and total questions
- 📌 User feedback: Provide immediate feedback after each answer
Test Your Knowledge
Test what you've learned about getting user input:
What's Next?
Now that you can handle user input effectively, you're ready to explore text formatting. Learn how to create professional, well-formatted output that enhances the user experience of your applications.
Ready to continue? Check out our lesson on Text Formatting.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.