Skip to content

[BEGINNER] Add Input Validation to All User Input Functions #1900

@hackdartstorm

Description

@hackdartstorm

🔒 Complete Guide: Input Validation in Python

📖 Problem Statement

Issue: Missing input validation across the Python learning codebase causes programs to crash when users enter invalid data.

Difficulty: Beginner
Category: Error Handling, User Input, Best Practices
Impact: HIGH - Affects 50+ beginner programs
Files: Multiple files in basics/ folder


💡 Real-World Analogy

Think of input validation like a bouncer at a club:

  • 🚫 Doesn't let in troublemakers (invalid input)
  • ✅ Welcomes valid guests (correct input)
  • 🛡️ Keeps everyone safe (prevents crashes)

Or like a recipe that specifies ingredients:

  • 📝 "Add 2 eggs" - not "add some stuff"
  • ✅ Clear expectations = successful outcome
  • ❌ Vague instructions = cooking disaster

📝 Examples of the Problem

❌ Current Code (NO Validation)

# basics/02_variables_types/01_arithmetic.py
a = int(input("Enter the Number : "))
b = int(input("Enter the Number : "))
result = a + b
print(f"Sum: {result}")

What happens with invalid input:

User Input Result User Experience
"5" ✅ Works: 10 Good
"abc" ❌ ValueError crash Terrible
"" (empty) ❌ ValueError crash Terrible
"12.5" ❌ ValueError crash Confusing
" 5 " ✅ Works: 10 Good

🧠 Key Concepts

1. Type Validation

Check input is correct data type

2. Range Validation

Check number is within acceptable range

3. Format Validation

Check input matches expected pattern

4. Length Validation

Check string length meets requirements


💻 Solution Approaches

Approach 1: Basic Try-Except (Beginner)

def get_valid_integer(prompt="Enter a number: "):
    """Get valid integer input with basic validation."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("❌ Invalid input! Please enter a whole number.")
        except KeyboardInterrupt:
            print("\n👋 Program interrupted.")
            exit(0)

# Usage
age = get_valid_integer("Enter your age: ")

Pros: Simple, easy to understand
Cons: No range checking


Approach 2: Validation Function (Intermediate)

from typing import Tuple, Optional

def validate_integer(value: str, min_val: Optional[int] = None, 
                     max_val: Optional[int] = None) -> Tuple[bool, str]:
    """Validate integer with optional range."""
    try:
        num = int(value)
        if min_val is not None and num < min_val:
            return False, f"Value must be at least {min_val}"
        if max_val is not None and num > max_val:
            return False, f"Value must be at most {max_val}"
        return True, ""
    except ValueError:
        return False, "Must be a valid integer"

def get_validated_integer(prompt="Enter: ", min_val=None, max_val=None):
    """Get validated integer input."""
    while True:
        value = input(prompt)
        is_valid, error = validate_integer(value, min_val, max_val)
        if is_valid:
            return int(value)
        print(f"❌ {error}")

# Usage with range
age = get_validated_integer("Enter age (1-100): ", min_val=1, max_val=100)

Pros: Reusable, range checking, clear errors
Cons: More code


Approach 3: Comprehensive Testing

def test_input_validation():
    """Test all validation scenarios."""
    from io import StringIO
    import sys
    
    # Test 1: Valid integer
    sys.stdin = StringIO("5\n")
    result = get_valid_integer("Enter: ")
    assert result == 5
    print("✓ Test 1 passed")
    
    # Test 2: Invalid then valid
    sys.stdin = StringIO("abc\n123\n")
    result = get_valid_integer("Enter: ")
    assert result == 123
    print("✓ Test 2 passed")
    
    # Test 3: Range validation
    sys.stdin = StringIO("150\n25\n")
    result = get_validated_integer("Enter: ", min_val=1, max_val=100)
    assert result == 25
    print("✓ Test 3 passed")
    
    # Test 4-10: More edge cases...
    # (Empty input, negative, floats, whitespace, etc.)
    
    print("\n🎉 All tests passed!")

📚 Learning Resources

  1. Python Input Validation - Real Python
  2. Error Handling - Official Docs
  3. Defensive Programming - Wikipedia

❓ Common Questions

Q: Why validate input?

A: Prevents crashes, improves UX, catches errors early

Q: How much validation is enough?

A: Based on context - calculator needs numbers, age needs range 0-150

Q: Isn't validation annoying?

A: Good validation is HELPFUL, not annoying. Give clear error messages!

Q: How to test validation?

A: Use StringIO to simulate input in tests


✅ Acceptance Criteria

  • All user input functions have validation
  • At least 2 validation approaches shown
  • 10+ test cases pass
  • Error messages are helpful
  • Range validation where appropriate
  • Type hints included
  • No crashes on invalid input

🤝 How to Contribute

  1. Fork the repository
  2. Find files: grep -r "int(input" basics/
  3. Add validation using approaches above
  4. Test with valid and invalid inputs
  5. Commit: git commit -m "Fix #1900: Add input validation"
  6. Create PR

Difficulty: Beginner
Impact: HIGH - 50+ files
Time: 2-3 hours

Ready to make our codebase robust? 🚀

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions