6  Input

6.1 The Wall

AI built you a program that asked the user for their age. They typed “twenty-five” and it crashed. You asked AI to fix it. It added a try/except that silently ignored the error. Now the program did not crash, but it also did not work. The user typed invalid input and the program carried on as if nothing happened.

AI’s default approach to user input is either “assume it is perfect” or “catch everything and ignore it.” Neither is acceptable. You need to understand how input() works and how to validate what comes back.

This chapter fixes that.

6.2 Thinking Session

6.2.1 Getting Oriented

NoteThinking Session Prompt

How does Python’s input() function work? I know it reads from the keyboard, but what type does it return? And what happens if the user types nothing and just presses Enter?

Your AI should emphasise that input() always returns a string, even if the user types a number. An empty Enter returns an empty string "", not None. This is the source of most input-related bugs in AI-generated code.

6.2.2 Go Deeper

NoteThinking Session Prompt

What are good patterns for validating user input in Python? I want to handle these cases: - User types nothing (empty input) - User types the wrong type (text when I need a number) - User types something outside the expected range

Show me a robust pattern I can reuse, not just a simple try/except that ignores errors.

TipWhat to Look For

The robust pattern is a validation loop: keep asking until input is valid. This typically uses while True with a break when input passes validation. Your AI should show this pattern rather than a single try/except.

NoteThinking Session Prompt

When I look at AI-generated code, I often see input().strip().lower() chained together. What does each part do, and why is this pattern so common?

6.2.3 Challenge It

NoteThinking Session Prompt

What is wrong with this input validation code?

age = input("Enter your age: ")
if age > 0 and age < 150:
    print(f"You are {age} years old")
TipWhat to Look For

age is a string (from input()), so age > 0 compares a string to an integer. This raises a TypeError in Python 3. The fix is age = int(input("Enter your age: ")) or validating and converting separately. AI generates this exact bug frequently.

6.2.4 What You Should Have Learned

  • input() always returns a string, even for numbers
  • Empty input returns "", not None
  • .strip() removes whitespace, .lower() normalises case
  • Validation loops (while True + break) are better than silent try/except
  • Chain methods: input().strip().lower() is idiomatic Python

6.3 The Gap

You now understand the most common source of bugs in AI-generated interactive programs: input that is not validated or not converted. When you see AI code that uses input(), you can immediately check whether it handles empty input, wrong types, and out-of-range values.

In the Building Session, you will make your chatbot handle bad input gracefully instead of crashing or ignoring errors.

6.4 Building Session

6.4.1 The Spec

Add input validation to your chatbot:

  • Handle empty input (user just presses Enter)
  • Clean up input with strip() and lower() for comparisons
  • Add a “help” command that lists available commands
  • Validate any numeric input with a proper loop

6.4.2 Prompt It

NoteBuilding Session Prompt

Update my chatbot to v0.6. Add input validation:

  • If the user enters empty input (just presses Enter), prompt them again with a helpful message instead of treating it as a message
  • Use .strip() on all input to handle accidental spaces
  • Use .lower() for command matching (quit, help)
  • Add a “help” command that lists: quit, help
  • When checking for numbers, if conversion fails, respond with a message about the input being text, do not silently ignore it

Keep the existing features from v0.5 (welcome screen, name, message count, number recognition).

6.4.3 Read the Code

Your AI will produce something like this:

"""PyBot v0.6: Input validation."""
BOT_NAME = "PyBot"
VERSION = "0.6"
WIDTH = 50
COMMANDS = ["quit", "help"]

print("=" * WIDTH)
print(f"{BOT_NAME:^{WIDTH}}")
print("=" * WIDTH)

user_name = input(f"{BOT_NAME}: What's your name? ").strip()
while not user_name:
    user_name = input(f"{BOT_NAME}: Please enter your name: ").strip()

print(f"{BOT_NAME}: Nice to meet you, {user_name}!")
message_count = 0

while True:
    user_input = input(f"{user_name}: ").strip()

    if not user_input:
        print(f"{BOT_NAME}: Say something! Type 'help' for commands.")
        continue

    command = user_input.lower()

    if command == "quit":
        print(f"{BOT_NAME}: Goodbye, {user_name}!")
        break
    elif command == "help":
        print(f"{BOT_NAME}: Commands: {', '.join(COMMANDS)}")
        continue

    message_count += 1

    try:
        number = int(user_input)
        response = f"{number} is {'even' if number % 2 == 0 else 'odd'}"
    except ValueError:
        response = f"Interesting. '{user_input}'"

    print(f"{BOT_NAME}: {response} (msg #{message_count})")
TipWhat to Notice

The name input uses a while not user_name loop, keeps asking until something is entered. .strip() is called on every input() to remove accidental spaces. command = user_input.lower() creates a normalised version for comparison without changing the display. continue skips to the next loop iteration for empty input and help commands.

6.4.4 Stretch It

NoteBuilding Session Prompt

Add an “age” command that asks the user for their age. Use a validation loop that keeps asking until they enter a valid number between 1 and 150.

6.5 Your Chatbot So Far

  • Ch 1: Basic loop with greeting and quit
  • Ch 2: Docstring, constants, comments
  • Ch 3: Recognises numbers vs text
  • Ch 4: Remembers user name, tracks messages
  • Ch 5: Formatted welcome screen
  • Ch 6: Input validation, help command, strip/lower

6.6 Quick Reference

# input() always returns a string
name = input("Name: ")           # str
age = int(input("Age: "))        # convert to int

# Clean input
text = input().strip()           # remove whitespace
text = input().strip().lower()   # normalise

# Validation loop
while True:
    value = input("Enter a number: ").strip()
    try:
        number = int(value)
        break                    # valid, exit loop
    except ValueError:
        print("That's not a number. Try again.")

# Empty check
if not user_input:               # empty string is falsy
    print("You didn't type anything")