Variables and Type Hints — Storing Data with Specifications
What Are Variables?
Imagine you're a restaurant manager writing down orders. Instead of saying "The customer ordered a coffee," you might write:
Order #5: coffee
Now you have a name (Order #5) for the data (coffee). You can refer to it later without repeating the whole sentence.
Variables work exactly the same way. A variable is a named container that holds data. It lets you:
- Store data — Save information so you don't lose it
- Name data meaningfully — Use descriptive names like
customer_nameinstead of remembering it's "in position 3 of some list" - Reuse data — Refer to it as many times as you need
- Change data — Update what it holds whenever you need to
In Chapter 13, you learned how to print messages directly:
print("Hello, World!")
Now we're going to store data first, then print it:
message: str = "Hello, World!"
print(message)
That second version is more powerful because the data is named and reusable. Let's explore why.
Concept: Storing Data Without Type Hints
Before we talk about type hints, let's see how Python lets you create variables:
# Simple variables - Python figures out the type
name = "Alex"
age = 25
height = 5.8
is_student = True
What's happening here?
name = "Alex"— Creates a variable callednameand stores the text"Alex"age = 25— Creates a variable calledageand stores the number25height = 5.8— Creates a variable calledheightand stores a decimal numberis_student = True— Creates a variable calledis_studentand storesTrueorFalse
The = is called the assignment operator. It means "store this value in this variable."
But here's the problem: If you look at age = 25 later, you might wonder, "Is 25 a temperature? A score? A count of something?" The code doesn't explain what the data means.
That's where type hints come in.
Concept: Type Hints as Specifications
A type hint is a note that says what type of data a variable holds. It's like adding a label to a jar:
# Variables with type hints - we describe what data means
name: str = "Alex"
age: int = 25
height: float = 5.8
is_student: bool = True
Let's break down the pattern age: int = 25:
age— The variable name (what we're storing): int— The type hint (saying "this will be an integer, a whole number")= 25— The value (what we're storing)
Read it like this: "age is an integer, and it equals 25."
The Four Main Data Types You'll Use
| Type | What It Holds | Examples | Type Hint |
|---|---|---|---|
| str (string) | Text | "Alex", "hello", "2025" | name: str |
| int (integer) | Whole numbers | 25, 0, -5, 1000 | age: int |
| float (floating-point) | Decimal numbers | 5.8, 3.14, -2.5 | height: float |
| bool (boolean) | True or False | True, False | is_active: bool |
Why Type Hints Matter
Type hints do THREE important things:
1. Clarity for humans — When you read age: int = 25, you instantly know age is a whole number, not a temperature or percentage.
2. A specification for AI — Type hints are embedded specifications. When you ask Claude or Gemini "What does this variable mean?", the type hint is the first clue. For example:
email: str = "[email protected]"tells AI, "This is text that should look like an email"account_balance: float = 150.50tells AI, "This is money (a decimal number)"
3. Catch mistakes early — Tools can check if you're using a variable correctly. If you write age: int = "twenty-five" (storing text in an integer variable), Python's type checker says, "Wait, that's not right."
In AI-native development, clear specifications are MORE valuable than memorized syntax. Type hints are how you specify data intent to your AI collaborator.
Code Example 1: Basic Variables with Type Hints
Here's how to create your first variables with type hints:
# Storing information about a person
name: str = "Alex"
age: int = 25
height: float = 5.8
is_student: bool = True
# Storing information about a product
product_name: str = "Python Book"
price: float = 29.99
in_stock: bool = True
quantity_remaining: int = 45
Specification: Declaring variables that describe real-world data
AI Prompt Used: "Create variables with type hints for a student profile (name, age, gpa, is_full_time). Use appropriate types for each."
Generated Code:
# Student profile with type hints
student_name: str = "Jordan"
student_age: int = 19
student_gpa: float = 3.85
is_full_time: bool = True
Validation Steps:
- ✓ Each variable has a name describing what it stores
- ✓ Each has a type hint (
str,int,float,bool) - ✓ Each has a value matching the type hint
- ✓ Code follows the pattern:
name: type = value
Code Example 2: Displaying Variables with print()
Now let's use print() from Chapter 13 to display variables:
# Create variables with type hints
name: str = "Alex"
age: int = 25
height: float = 5.8
is_student: bool = True
# Display each variable
print(name) # Output: Alex
print(age) # Output: 25
print(height) # Output: 5.8
print(is_student) # Output: True
Try this yourself:
- Create a file called
variables.py - Copy the code above
- Run it:
python variables.py - Change the values and run again — you'll see the new values printed
Code Example 3: Combining Variables with F-Strings
F-strings (f-formatted strings) let you combine variables and text. This is a preview of Chapter 16, but it's useful to see how type hints work with real output:
# Variables with type hints
name: str = "Alex"
age: int = 25
is_student: bool = True
# Combining variables in sentences
print(f"Hello, {name}!")
print(f"You are {age} years old.")
print(f"Are you a student? {is_student}")
# More complex sentence
print(f"{name} is {age} years old and is a student: {is_student}")
Expected output:
Hello, Alex!
You are 25 years old.
Are you a student? True
Alex is 25 years old and is a student: True
Key insight: Notice how the type hints (name: str, age: int, is_student: bool) let us use these variables confidently in sentences. The type hint is a specification that says, "I know what type this is, so I know how to use it."
Practice Exercise 1: Create Variables for Your Profile
Create a Python file with variables describing you. Use type hints for each:
# Your turn! Fill in the values.
your_name: str = "..."
your_age: int = ...
your_favorite_food: str = "..."
your_height_in_feet: float = ...
are_you_learning_to_code: bool = ...
# Print them all
print(your_name)
print(your_age)
print(your_favorite_food)
print(your_height_in_feet)
print(are_you_learning_to_code)
Success criteria:
- All variables have type hints
- All variables have appropriate types for their values
- All variables print without errors
- You can change the values and see the output update
Practice Exercise 2: Create Variables for Different Data Types
Create one variable for each data type. Challenge yourself to choose meaningful names:
# String variables (text)
favorite_color: str = "..."
best_friend_name: str = "..."
# Integer variables (whole numbers)
birth_year: int = ...
favorite_number: int = ...
# Float variables (decimal numbers)
favorite_temperature: float = ...
average_test_score: float = ...
# Boolean variables (True/False)
do_you_like_python: bool = ...
have_you_coded_before: bool = ...
# Now print them all in a sentence
print(f"My favorite color is {favorite_color}.")
print(f"I was born in {birth_year}.")
print(f"I like Python: {do_you_like_python}")
Success criteria:
- All 8 variables have correct type hints
- Values match their types (strings in quotes, numbers without quotes, True/False for booleans)
- All variables print without errors
- Each sentence reads naturally
Practice Exercise 3: The Type-Hint Challenge
Create variables for a simple game character. Choose the right type for each attribute:
character_name: str = "Knight"
health_points: int = 100
mana_points: int = 50
speed: float = 7.5
is_alive: bool = True
experience: int = 0
# Display the character's status
print(f"{character_name} has {health_points} HP and {mana_points} mana.")
print(f"Speed: {speed}, Alive: {is_alive}, Experience: {experience}")
Questions to think about:
- Why is
health_pointsanintand not afloat? - Why is
speedafloatand not anint? - Why is
is_aliveabool(True/False) instead of text? - What would happen if you tried
health_points: str = 100? (Try it and see what error you get—don't worry if there's an issue, just observe.)
Success criteria:
- All variables have the correct type hint for their data
- The character display works without errors
- You can explain why each type was chosen
Common Pitfalls
Pitfall 1: Forgetting Quotes for Strings
# WRONG - string needs quotes
name: str = Alex
# RIGHT - string has quotes
name: str = "Alex"
If you see an error like NameError: name 'Alex' is not defined, you forgot quotes.
Pitfall 2: Putting a Decimal in an Integer
# WRONG - int should be a whole number
age: int = 25.5
# RIGHT - use float for decimals
age: float = 25.5
# OR keep int if you want whole numbers
age: int = 25
Pitfall 3: Type Hint Doesn't Match the Value
# WRONG - says int but stores text
age: int = "25"
# RIGHT - either change the type hint or the value
age: str = "25" # if it's text
age: int = 25 # if it's a number
Pitfall 4: Using the Wrong Capitalization for Booleans
# WRONG - lowercase true
is_student: bool = true
# RIGHT - Python uses True and False (uppercase)
is_student: bool = True
Why This Matters for AI-Driven Development
Here's the big picture: Type hints are how you write specifications. When you write:
user_email: str = "[email protected]"
purchase_amount: float = 99.99
is_premium_member: bool = True
You're telling any AI collaborator (Claude, Gemini, Copilot):
- What data you have — email (text), amount (money), membership status (yes/no)
- What it means — The variable names describe purpose; the type hints describe structure
- How to use it safely — Text gets email validation, numbers can do math, booleans trigger yes/no logic
When you ask Claude Code "How do I validate this email?" it immediately knows user_email is text and suggests string validation. When you ask "How do I add tax to this purchase?" it knows purchase_amount is a decimal number and can calculate correctly.
Type hints are embedded specifications. Clear specifications make AI collaboration more powerful.
Try With AI
Use this section to reinforce your learning by applying the lesson with an AI tool. You've seen how variables with type hints describe data. Now let's explore this deeper with your AI collaborator.
Using Claude Code, Gemini CLI, or ChatGPT (web):
Prompt Set
Prompt 1: Understand Variable Purpose
Copy this prompt and paste it into your AI tool:
You learned about print() in Chapter 13. Now explain what a variable is
in 2-3 sentences. Use a real-world analogy (like a labeled jar, a mailbox,
or a storage box). Why do we need variables instead of just using print()
with values directly?
Expected outcome: AI explains variables using a concrete analogy, clarifying why labeling data is useful.
Prompt 2: Decode Type Hints
What does this line of code mean? Break it down piece by piece:
age: int = 25
Explain what "age", ": int", and "= 25" each mean. Why do we add ": int"
to the variable?
Expected outcome: AI explains that the type hint describes data structure, separating "what it is" (int) from "what value it holds" (25).
Prompt 3: Explore Data Types
Show me 5 examples of variables with type hints for different data.
Create variables for: a person's name, their age, their weight in pounds,
whether they exercise regularly, and the date they joined. Choose the
correct type (str, int, float, or bool) for each. Explain why you chose
each type.
Expected outcome: AI creates realistic variables and explains type reasoning. You'll see patterns: text uses str, whole numbers use int, decimals use float, yes/no uses bool.
Prompt 4: Type Hints as Specifications (Stretch)
Here's a question: How does "age: int = 25" help you and me (an AI)
understand this code better than just "age = 25"? Why is the type hint
a specification? How does clarity help when learning with AI as your partner?
Expected outcome: AI explains that type hints reduce ambiguity, enable validation, and allow AI to suggest context-aware help. This connects variables to the broader concept of specification-driven development.
Safety & Ethics Note
When exploring code with AI, always ask "Why?" before using it. Type hints are clear because they reduce guessing. As you write more code, you'll notice that clarity is collaboration—clear code helps you, helps teammates, and helps AI understand your intent. This is why the book emphasizes specifications as the primary skill, not syntax memorization.
Next Self-Directed Variation
After working through these prompts:
- Create a variable for something in your own life (a hobby, a possession, a preference)
- Write it with a type hint
- Share it with your AI partner and ask: "Does this type hint match my intent? Could someone (or an AI) understand what this variable represents?"
- Experiment: Change the type hint to the wrong type (e.g.,
hobby: int = "painting") and ask your AI, "What's wrong with this?"
This practice builds your ability to think in specifications—the foundation of AI-native development.