4  Variables

4.1 The Wall

You asked AI to “make a chatbot that remembers the user’s name.” It gave you 40 lines of code with user_name, bot_name, message_count, last_response, _internal_state, and MAX_RETRIES. It worked, until you tried to change something and everything broke. You renamed a variable in one place but not another. You changed a value that turned out to be used in three different places.

You could not tell which variables mattered, which were temporary, and which were constants you should not touch. Without understanding how variables work, AI-generated code is a minefield of names you cannot safely modify.

This chapter fixes that.

NoteComing from Think Python?

If you worked through Think Python, Direct AI, you already used variables in projects like the Temperature Converter and Quiz Game. This chapter makes that knowledge systematic, explaining the rules and patterns behind what you practised.

4.2 Thinking Session

4.2.1 Getting Oriented

NoteThinking Session Prompt

Explain Python variables to me, but do not use the “box that holds a value” metaphor. I want to understand what actually happens when I write x = 5. Also explain why Python lets me write x = 5 and then x = "hello" on the next line, is that a feature or a problem?

Your AI should talk about name binding. x = 5 binds the name x to the integer object 5. The “box” metaphor is misleading because it implies the variable contains the value. In Python, variables are labels pointing to objects. If your AI uses the box metaphor anyway, push back.

4.2.2 Go Deeper

NoteThinking Session Prompt

Show me three examples where choosing bad variable names would make AI-generated code confusing to modify. Then show the same code with good names. What naming conventions does Python use?

TipWhat to Look For

The pattern: snake_case for variables and functions, UPPER_CASE for constants, PascalCase for classes. These are not just style. They carry meaning. When you see MAX_RETRIES in AI-generated code, the uppercase tells you it is a constant that should not change.

NoteThinking Session Prompt

What is the difference between x = 5 and x == 5? When I am reading AI-generated code, how do I know which one I am looking at? And what about x += 1, what does that do?

4.2.3 Challenge It

NoteThinking Session Prompt

What is wrong with this code, and why would AI likely generate it?

name = "Alice"
def greet():
    print(name)
    name = name + "!"
TipWhat to Look For

This is a scope trap. The name = name + "!" inside the function creates a local variable that shadows the global one. Python sees the assignment and treats name as local for the entire function, so print(name) fails with UnboundLocalError. AI generates this pattern regularly.

4.2.4 What You Should Have Learned

  • Variables are names bound to objects, not boxes holding values
  • Assignment (=) vs equality (==) vs augmented assignment (+=)
  • Python naming conventions: snake_case, UPPER_CASE, PascalCase
  • Dynamic typing means variables can change type, powerful but requires attention
  • Scope exists and can cause subtle bugs

4.3 The Gap

You can now read AI-generated code and understand what the variable names mean, why they are structured the way they are, and what happens when values change. That is the difference between someone who copies AI output and someone who can safely modify it.

In the Building Session, you will add memory to your chatbot, and understand every variable AI creates.

4.4 Building Session

4.4.1 The Spec

Add state tracking to your chatbot:

  • Store the user’s name (ask for it at the start)
  • Track how many messages have been exchanged
  • Use named constants for bot configuration
  • Reference the stored name in responses

4.4.2 Prompt It

NoteBuilding Session Prompt

Here is my chatbot (v0.3). Update it to v0.4:

"""PyBot v0.3: Recognises numbers vs text."""
BOT_NAME = "PyBot"
VERSION = "0.3"
print(f"Hello! I'm {BOT_NAME} v{VERSION}.")
print("Type 'quit' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() == "quit":
        print(f"{BOT_NAME}: Goodbye!")
        break
    try:
        number = int(user_input)
        response = f"{number} is {'even' if number % 2 == 0 else 'odd'}"
    except ValueError:
        response = f"You said '{user_input}'"
    print(f"{BOT_NAME}: {response}")

Add these features using variables: - Ask the user’s name at the start, store in user_name - Add message_count that increments each turn - Include user’s name and count in responses - Update VERSION to “0.4”

Keep it simple. No functions, no classes.

4.4.3 Read the Code

Your AI will produce something like this:

"""PyBot v0.4: Remembers your name, tracks messages."""
BOT_NAME = "PyBot"
VERSION = "0.4"

print(f"Hello! I'm {BOT_NAME} v{VERSION}.")
user_name = input(f"{BOT_NAME}: What's your name? ")
print(f"{BOT_NAME}: Nice to meet you, {user_name}!")
print("Type 'quit' to exit.")

message_count = 0

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

    if user_input.lower() == "quit":
        print(f"{BOT_NAME}: Goodbye, {user_name}!")
        print(f"We exchanged {message_count} messages.")
        break

    message_count += 1

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

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

user_name stores the result of input(). It persists across the entire loop. message_count starts at 0 and uses += 1 to increment. Both BOT_NAME and VERSION are constants (uppercase) set once and never changed. The f-strings reference these variables by name, change the variable, change every response.

4.4.4 Stretch It

NoteBuilding Session Prompt

Add a favourite_topic variable that starts as None. When the user mentions “python” or “coding”, set it to that word. In future responses, if favourite_topic is set, occasionally mention it.

Notice how your AI handles the None initial value and the is not None check. This pattern appears constantly in AI-generated code.

4.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 message count

4.6 Quick Reference

# Assignment
x = 5
x = "hello"        # dynamic typing
x += 1              # augmented assignment
x, y = 1, 2         # multiple assignment
x, y = y, x         # swap

# Constants (convention)
BOT_NAME = "PyBot"
MAX_RETRIES = 3

# None
x = None
if x is not None:
    print(x)