03. Variables and Types

Chapter 3 of 36 · 20 min

Python Is Dynamically Typed

Python variables have types, but you do not declare them. The interpreter figures it out at runtime:

x = 42          # int
y = 3.14        # float
name = "GPT-4"  # str
active = True   # bool

The Basic Types

Type Example Mutable
int 42 No
float 3.14 No
str "hello" No
bool True No
list [1, 2, 3] Yes
dict {"key": "value"} Yes
None None No

Strings Are Objects

Strings have methods. This is normal Python:

model_name = "gpt-4"
print(model_name.upper())           # GPT-4
print(model_name.replace("-", ""))  # gpt4
print(model_name.startswith("gpt")) # True

Type Conversion

Python does not auto-convert between types:

# This fails:
result = "Total: " + 42  # TypeError

# Fix it:
result = "Total: " + str(42)  # "Total: 42"

# Number conversion:
int("42")    # 42
float("3.14") # 3.14

F-Strings for Interpolation

F-strings (formatted string literals) are the modern way to embed variables:

model = "gpt-4"
tokens = 1000
cost_per_1k = 0.03

message = f"{model} costs ${cost_per_1k:.2f} per 1K tokens for {tokens} tokens"
print(message)
# gpt-4 costs $0.03 per 1K tokens for 1000 tokens

The :2f formats the float to 2 decimal places.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Write a script that:

  1. Creates variables for an AI model's name, context window size, and cost per token
  2. Prints a formatted description using an f-string
  3. Converts the cost per token from a string to a float and performs a calculation