g↗genai/ learner
Python for AI / Lesson 01

Variables and Data Types

Every prompt, temperature setting, and model response in Python is stored under a name and shaped by its data type. Understanding how Python names values and checks types is the first step in building reliable AI systems.

Concept + interactive labBeginner friendly

Names point to values in memory.

When you write Python code to interact with an AI model, you frequently work with configuration parameters: token limits, temperatures, and system prompts. To keep track of these values, Python uses variables.

A variable in Python is not a permanent box that can only hold one kind of data. Instead, think of a variable as a sticky note or name tag attached to an object in your computer's memory. You assign a name using the single equals sign (=):

Assignment mechanism: The single = operator evaluates the expression on its right-hand side first, creates that value in memory, and then attaches the name on the left to it.

This is fundamentally different from mathematical equality. In algebra, the statement count = count + 1 is an impossible equation. In Python, it is a routine operation:

# 1. Look up current value (3), compute 3 + 1 = 4

count = 3

count = count + 1 # count now points to 4

Reassigning a variable does not overwrite the number 3 in memory; it simply moves the name tag count to point to the new number 4.

Infographic showing Python's memory model in two panels. Left panel illustrates variables as name tags pointing to objects in memory: 'max_tokens' and 'prompt_limit' point to the same integer object 500, 'temperature' points to float 0.7, and 'count' points to 4 while leaving previous value 3 unreferenced for garbage collection. Right panel illustrates that types belong to values rather than names: 'raw_limit' points to string object '500' while 'token_budget' points to integer object 500, showing that types live inside the objects in memory.
Python memory model: variables are name tags pointing to objects in memory. Reassignment moves the tag; types live inside the values, not the names.

Four primitive types power AI code.

Every object in Python has a type. The type tells Python what the data represents, how much memory it occupies, and what operations (such as addition or concatenation) are allowed. Four primitive types appear in nearly every AI script:

strText / Strings
prompt = "Summarize this"

Sequences of characters wrapped in quotes. Used for user prompts, system instructions, and raw model completions.

intIntegers
max_tokens = 500

Whole numbers without decimal points. Used for discrete counts, token budgets, retry limits, and batch sizes.

floatDecimals
temperature = 0.7

Numbers with decimal points. Used for model sampling parameters, probability scores, loss metrics, and embeddings.

boolBooleans
stream = True

Logical truth values: either True or False (capitalized, without quotes). Used for feature flags, safety checks, and API switches.

You can inspect the type of any variable at runtime using Python's built-in type() function:

type(500) # returns <class 'int'>

type(0.7) # returns <class 'float'>

type("gemini") # returns <class 'str'>

type(True) # returns <class 'bool'>

Inspect variables and types in the sandbox.

Use the interactive sandbox below to explore how Python assigns and inspects AI configuration parameters. Select different parameters, test what happens when a number is accidentally wrapped in quotes, and test operations like addition and API validation.

AI Parameter & Type Sandbox

Live Inspection
# 1. Assignment in Python code

max_tokens = 500

2. Mental Model: Name points to Object in Memory

Variable Name
max_tokens
<class 'int'>500

Runtime Inspection

type(max_tokens)
<class 'int'>
repr(max_tokens)
500

3. Test an Operation

max_tokens + 100 # Result: 600

Numeric addition: Python adds the integers together, producing 600.

Quotes create text, not numbers.

One of the most frequent bugs in AI applications involves confusing a number with a string of digits:

  • 500 is an int. Python treats it as a mathematical quantity and can add, subtract, and compare it.
  • "500" is a str. Python treats it as a sequence of text characters (the character '5' followed by two zeros).

Python behaves differently depending on the types involved:

# Adding two integers does arithmetic

500 + 100 # 600

# Adding two strings concatenates (glues) text together

"500" + "100" # "500100"

# Adding a string to an integer is forbidden in Python!

"500" + 100 # TypeError: can only concatenate str (not "int") to str

Unlike some programming languages (like JavaScript) that quietly convert strings to numbers on the fly, Python is strongly typed. It refuses to guess your intention and raises a TypeError if you try to combine incompatible types.

The boolean quote trap: In Python, True is a boolean truth value, while "True" and "False" are text strings. Because Python treats any non-empty string as "truthy", running bool("False") evaluates to True! Always use the unquoted keywords True and False for boolean flags.

Converting types safely for model inputs.

When you read configuration values from environment variables (such as os.getenv("MAX_TOKENS")) or receive user inputs from web forms, the data almost always arrives as a str.

Before passing these values to an AI SDK or model API that expects numeric parameters, you must explicitly convert (or "cast") them:

import os

# Provide a fallback default string if unset

raw_limit = os.getenv("MAX_TOKENS", "1000") # type is str

# Explicitly cast to integer for the model API

max_tokens = int(raw_limit) # type is int (1000)

# Convert decimal strings to float

temperature = float("0.7") # type is float (0.7)

Two different errors can occur during configuration loading:

  • Missing variables (TypeError): If os.getenv("MAX_TOKENS") is unset without a default, it returns None. Passing None to int() raises a TypeError. Setting a fallback default string prevents this.
  • Invalid text (ValueError): If the string cannot be parsed as a number (such as int("unlimited")), Python raises a ValueError.

int("unlimited") # ValueError: invalid literal for int() with base 10

In production AI pipelines, converting and validating types early prevents malformed requests from reaching your model provider.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

An AI assistant script has the line: max_tokens = "250". Later in the script, the code executes: total_tokens = max_tokens + 50. What happens in Python, and why?
THE TAKEAWAY

Take this with you.

Variables are name tags that point to typed objects in memory, not fixed storage boxes. Python's four core primitive types (str, int, float, and bool) govern what operations are valid. Quotes turn numbers into text, and Python requires explicit conversion (such as int() or float()) when passing string inputs to numeric AI APIs.

Next up: Operators in Chapter P1 →