Lesson 3 of 3 · Python for AI
Python Basics: Variables, Types, and Print
The Story of Marcus's First Line of Code
Marcus Reeves had been a commercial real estate broker for fourteen years. He was good at his job -- he could walk into a building and estimate its value within five percent, negotiate a lease that made both sides feel like winners, and read a market trend months before his competitors noticed. What he could not do, or so he believed, was write code.
The idea of learning Python had been nagging at him for months. He kept reading about AI tools that could analyze property listings, predict rental yields, and automate the tedious market reports he spent every Sunday afternoon preparing. But every tutorial he found seemed to assume you already knew what a "variable" was, or that terms like "string" and "integer" were self-explanatory. They were not self-explanatory. Not to Marcus.
On a rainy Tuesday evening, after his third attempt at an online Python course that began with the sentence "Let's explore object-oriented paradigms," Marcus almost quit for good. He closed his laptop, poured a glass of bourbon, and stared at the ceiling.
Then he opened the laptop one more time. He opened the Python environment he had installed earlier that week -- just the simple IDLE editor that comes with Python -- and typed exactly five words:
He pressed Enter. And there, on the screen, in plain text, the computer said it back to him:
Marcus stared at the output. It was absurdly simple. He had typed an instruction, and the computer had followed it. No ambiguity. No negotiation. No misinterpretation. He had told the machine to print his name, and it did exactly that.
He typed another line:
Then another:
Marcus sat up in his chair. He had just created a variable, performed a calculation, and displayed the result -- all in three lines of code. No one had given him permission. No one had certified him. He had just... done it.
That moment -- the moment you see something you wrote produce a result on screen -- is one of the most powerful experiences in learning to code. It is the moment the computer stops being a mysterious black box and starts becoming a tool you control.
This lesson will give you that same moment. By the end, you will understand how Python stores information, how it thinks about different types of data, and how to make it talk to you. You will also build something real: a simple AI cost calculator that computes how much money an API call will cost based on token count and pricing.
Let's start with the single most important concept in all of programming.
Variables: Giving Names to Things
What Is a Variable?
A variable is a name you assign to a piece of data so you can use it later. That's it. No deeper mystery. Think of it like a label on a file folder -- the label tells you what's inside, and you can refer to the folder by its label instead of describing its contents every time.
In Python, you create a variable with a single equals sign:
This line says: "Create a label called city and store the text Denver inside it." From this point forward, anywhere you write city in your code, Python will substitute the value "Denver".
Notice that when we print city, we do not put quotes around it. If we did, Python would print the literal word "city" instead of the value stored inside the variable:
This distinction -- between the name of the variable and the value inside it -- is one of the first things every programmer must internalize.
Use Python Basics: Variables, Types, and Print in a low-risk branch or scratch project first. That keeps the lesson concrete without making your first attempt carry production pressure.
Naming Rules and Conventions
Python has a few rules about variable names:
The Python convention is to use snake_case -- lowercase words separated by underscores. You will see this everywhere in professional Python code, and in every AI library you will use later in this track.
Good variable names are like good file labels -- they tell you exactly what's inside without needing to open the folder. Compare these:
Take the extra two seconds to write a clear name. Your future self will thank you when you reopen this code in three months.
Reassigning Variables
Variables are not permanent. You can change what they hold at any time:
That last line might look strange if you think of = as "equals" in the mathematical sense. In Python, = means assignment, not equality. The line price = price + 50 says: "Take the current value of price (200), add 50, and store the result (250) back into price."
Data Types: How Python Thinks About Information
Every value in Python has a type -- a category that determines what you can do with it. Think of it like the difference between a phone number and a street address. They are both pieces of information, but you would not try to navigate to a phone number.
Strings -- Text
Strings are sequences of characters wrapped in quotes. You can use either single quotes or double quotes -- Python treats them identically:
Strings are the most important data type for AI work, because prompts and responses are strings. Everything you send to an AI model is text. Everything that comes back is text.
If Python Basics: Variables, Types, and Print becomes part of a recurring workflow, document the exact trigger, boundary, and verification step now. Future speed comes from clarity, not from memory.
Multi-line Strings
For longer text -- like AI prompts -- use triple quotes:
Triple-quoted strings preserve line breaks exactly as you write them. You will use these constantly when building prompts for AI models.
Integers -- Whole Numbers
Integers are numbers without decimal points:
You can do all the arithmetic you would expect:
Floats -- Decimal Numbers
Floats are numbers with decimal points:
Computers sometimes produce tiny rounding errors with floats. This is normal and rarely matters in practice, but it can surprise beginners:
For most AI work, this is irrelevant. If you need exact decimal math (for financial calculations, for example), Python has a Decimal module. For now, just be aware this quirk exists.
Booleans -- True or False
Booleans represent yes/no, on/off, true/false values:
Note the capital T and F -- True and False are Python keywords. Writing true (lowercase) will cause an error.
Booleans become essential when you start making decisions in your code (which we will cover in the next chapter on conditionals). For now, just know they exist and they only have two possible values.
Checking Types
If you are ever unsure what type a value is, use the type() function:
The print() Function: Making Python Talk
You have already been using print() -- it is how you see output from your code. But there is more to it than just printing a single value.
Printing Multiple Values
You can pass multiple items to print(), separated by commas. Python will automatically add a space between them:
Measure the Python Basics: Variables, Types, and Print Tradeoff
- Choose one task you repeat often.
- Run it with the model, cost, or performance setting discussed in this lesson.
- Record latency, quality, and cost so you can choose intentionally next time.
f-strings: The Professional Way to Format Output
f-strings (formatted string literals) are the modern, readable way to embed variables inside text. Put an f before the opening quote, then use curly braces {} around any variable or expression:
You can put any Python expression inside the curly braces -- not just variable names:
The :.2f part is a format specifier -- it means "show as a float with 2 decimal places." You will find these useful when displaying prices and percentages.
You do not need to memorize these. Bookmark this callout and come back when you need one.
Using print() for Debugging
One of the most practical uses of print() is debugging -- figuring out what is going wrong in your code. When something produces an unexpected result, add print() statements to see what Python is actually doing:
The print() statement reveals the bug immediately -- monthly_rent is a string "4500", not the number 4500. The quotes made all the difference.
Type Conversion: Translating Between Types
Sometimes you have data in one type and need it in another. Python provides built-in functions for converting between types:
When converting a float to an integer with int(), Python simply chops off the decimal -- it does not round. If you want proper rounding, use the round() function:
Why Type Conversion Matters for AI Work
When you work with AI APIs, data constantly moves between types. An API might return a token count as a string inside a JSON response. You need to convert it to an integer before you can do math with it. A price might arrive as a float that you need to display as a formatted string. Understanding type conversion is not abstract -- it is a daily practical skill.
Optimize One Repeated Task
- Take one expensive or slow Claude workflow from your week.
- Apply the optimization idea from this lesson to it once.
- Keep the change only if quality stayed acceptable while speed or cost improved.
Comments: Explaining Your Code
Comments are notes you write for humans -- Python ignores them completely. Use the # symbol:
When to Comment (and When Not To)
Good comments explain why you did something, not what the code does. If your code is well-named, the "what" should be obvious:
For multi-line explanations, you can stack comments or use a docstring:
Arithmetic Operations
Python supports all the math operations you would expect, plus a few useful extras:
Order of Operations
Python follows standard mathematical order of operations (PEMDAS). Use parentheses when you want to be explicit:
Practical Example: Real Estate Math
Python lets you use underscores in large numbers for readability. 1_200_000 and 1200000 are exactly the same value. Python ignores the underscores entirely -- they are just for human eyes. Use them freely in your code whenever a number has more than four digits.
Getting Input from Users
The input() function pauses your program and waits for the user to type something. Whatever they type comes back as a string -- always:
Since input() always returns a string, you must convert it if you need a number:
You can combine the conversion and input into one line:
If someone types "hello" when your code expects a number, int("hello") will crash with a ValueError. For now, just be aware of this. In a later lesson on error handling, you will learn how to protect against bad input using try/except blocks.
Common Beginner Mistakes (And How to Fix Them)
Every new programmer hits the same walls. Here are the ones you will encounter first, and exactly how to get past them.
Quick Check
What is the main benefit of using Python Basics: Variables, Types, and Print well in Claude Code?
Mistake 1: Mismatched or Missing Quotes
If your error message says SyntaxError: EOL while scanning string literal, it almost always means you forgot a closing quote.
Mistake 2: Using a Variable Before Defining It
Python reads your code from top to bottom. If you try to use a name before you have assigned a value to it, you get a NameError.
Mistake 3: Confusing = and ==
Using = when you mean == (or vice versa) is one of the most common bugs in programming. You will work with == more when you learn about conditionals.
Mistake 4: Trying to Do Math with Strings
Mistake 5: Forgetting Parentheses on Function Calls
Mistake 6: Indentation Errors
Python uses indentation (spaces at the start of a line) to structure code. In this lesson, you have not needed indentation yet, but you will the moment you write an if statement or a loop. For now, make sure every line of your code starts at the left margin unless a tutorial specifically tells you to indent.
Apply: Hands-On Practice
Now it is time to write code yourself. These exercises build on each other -- each one is slightly harder than the last.
Exercise 1: Your Digital Business Card
Create a Python script that stores your professional information in variables and prints a formatted business card. Use f-strings.
Run it and verify the output looks like a proper card. Then try changing "=" * 40 to "-" * 40 or "#" * 40 -- notice how * with a string repeats it. This is called string repetition.
Exercise 2: Type Detective
Predict the type of each value before running the code. Then run it and check your predictions:
Key insight: 42 and "42" are fundamentally different. The first is a number you can do math with. The second is text that happens to contain digit characters. Similarly, True (boolean) and "True" (string) are completely different types. The quotes make all the difference.
Exercise 3: Temperature Converter
Write a script that asks the user for a temperature in Fahrenheit and converts it to Celsius. The formula is: C = (F - 32) * 5/9
Test it with these known values:
- 32F should give 0.0C
- 212F should give 100.0C
- 98.6F should give 37.0C
Bonus: Add a line that also converts to Kelvin (K = C + 273.15).
Exercise 4: String Surgery
Practice string methods by running this code and observing each result:
Notice how you can chain string methods: .strip().lower() first removes whitespace, then converts to lowercase. Each method returns a new string that the next method operates on.
Mini-Project: AI Cost Calculator
Now let's build something practical -- a calculator that estimates how much an AI API call will cost. When you use AI models like Claude or GPT through their APIs (which you will learn to do later in this track), you pay based on the number of tokens processed. A token is roughly 3-4 characters of text.
Quick Check
After reading this lesson, what should you validate when applying Python Basics: Variables, Types, and Print?
Mini-Project: Build an AI Cost Calculator
Build this step by step. Type each section, run it, and make sure it works before moving to the next.
Step 1 -- Define pricing constants:
Step 2 -- Get user input:
Step 3 -- Calculate costs:
Step 4 -- Display results:
Test with these values: 500 input words, 300 output words, 100 calls. You should see costs in the range of a few cents to a few dollars -- AI APIs are remarkably affordable for most use cases.
Challenge extensions (if you want more practice):
- Add a third model (Claude Haiku: $0.00025 input, $0.00125 output per 1K tokens)
- Add a monthly projection (multiply by 22 working days)
- Add sales tax calculation at 8.5%
Key Takeaways
- A variable is a named label for a piece of data -- create one with
name = valueand Python figures out the type automatically - Python has four fundamental data types you will use constantly: strings (text in quotes), integers (whole numbers), floats (decimal numbers), and booleans (True/False)
- f-strings are the professional way to embed variables in text -- put
fbefore the quotes and wrap variables in curly braces:f"Hello, {name}" - The
print()function is both your primary output tool and your best debugging tool -- when something goes wrong, print your variables and their types to find the bug - Type conversion functions (
int(),float(),str()) translate between data types -- you will use these constantly when working with AI APIs that pass data as strings - Python uses
=for assignment (storing a value) and==for comparison (checking equality) -- confusing these is one of the most common beginner bugs - Comments (
#) explain the why behind your code, not the what -- good variable names should make the "what" obvious - The
input()function always returns a string, even if the user types a number -- convert it withint()orfloat()before doing math
Reflect: From Print Statement to Possibility
Let us return to Marcus. After his first evening writing Python, he did not immediately build anything that transformed his business. He went to bed having written a few dozen lines of code -- variables, print statements, some basic arithmetic. Nothing his spreadsheet could not have done.
But something had shifted. The next morning, over coffee, Marcus found himself thinking differently about his work. He looked at the market report he had to prepare and instead of seeing a tedious four-hour task, he saw a sequence of steps: gather rental data, calculate averages, compare to last quarter, format the output. Steps that could be described. Steps that could be automated. Steps that could be coded.
He did not know how to do any of that yet. He did not know about loops or functions or API calls. But he knew -- because he had experienced it the night before -- that he could give Python an instruction and it would follow it precisely. That was enough. That one fact, proven by the simple act of seeing Hello, Marcus appear on screen, had rewritten his mental model of what was possible.
This is the real value of what you learned in this lesson. The variables, types, and print statements are essential building blocks -- you will use every one of them in every program you write. But the deeper lesson is that you can make a computer do things by describing what you want in a structured way. That skill, the ability to think in steps and translate those steps into instructions, is what separates people who use AI tools from people who build with them.
In the next lesson, you will learn how to make Python decide things -- choosing different paths based on conditions, repeating actions across lists of data, and building reusable blocks of logic called functions. The real power of programming is about to begin.
But first, go run that AI cost calculator. Change the numbers. Break it on purpose and fix it. Every error message you see and resolve is a small victory. Every line of code you write -- even if it is just print("Hello") -- is proof that you belong here.
Use ← → to navigate, Space to mark complete