Variables & Data Types
Variables store data. Data types define what kind of data you're working with. Master these and you can represent anything in Python.
Learning Objectives
- Create variables and understand Python's dynamic typing
- Use the four primitive types: str, int, float, bool
- Convert between types with int(), float(), str(), bool()
- Use arithmetic and comparison operators
- Format strings with f-strings
- Understand None and when to use it
What Is a Variable?
A variable is a name that points to a value. Python is dynamically typed โ you don't declare the type, Python figures it out.
# Create variables โ no type declaration needed
name = "Alice" # str (string)
age = 28 # int (integer)
height = 5.7 # float (decimal number)
is_student = True # bool (True/False)
# Python infers the type automatically
print(type(name)) #
print(type(age)) #
print(type(height)) #
print(type(is_student)) #
Variable naming rules
- Must start with a letter or underscore (
_), not a number - Can contain letters, numbers, underscores:
my_var_2 - Case-sensitive:
nameandNameare different variables - Use snake_case (Python convention):
api_key, notapiKey - Never use Python keywords:
class,return,import,None
Strings (str)
Strings are text โ sequences of characters enclosed in quotes. You'll work with strings constantly when building AI apps (prompt text, API responses, user input).
# Three ways to create strings
single = 'Hello'
double = "World"
multi = """This is a
multi-line string.
Useful for long prompts."""
# String operations
greeting = single + " " + double # concatenation
repeated = "ha" * 3 # "hahaha"
length = len(greeting) # 11
# Accessing characters (0-indexed)
first = greeting[0] # "H"
last = greeting[-1] # "d" (last character)
# slicing: [start:stop] (stop is exclusive)
world = greeting[6:11] # "World"
# Useful string methods
"hello world".upper() # "HELLO WORLD"
" spaces ".strip() # "spaces"
"hello world".split() # ["hello", "world"]
",".join(["a", "b", "c"]) # "a,b,c"
"hello".replace("l", "r") # "herro"
F-Strings (Formatted Strings)
F-strings are the Pythonic way to embed variables and expressions in strings. You'll use them everywhere.
# Basic f-string โ prefix with 'f' and use {} for expressions
model = "GPT-4o"
tokens = 1500
cost = 0.0225
print(f"Model: {model}, tokens: {tokens}")
# Format numbers
print(f"Cost: ${cost:.4f}") # Cost: $0.0225
print(f"Tokens: {tokens:,}") # Tokens: 1,500
print(f"Percentage: {cost * 100:.2f%"}) # Percentage: 2.25%
# Expressions inside {}
print(f"2 + 3 = {2 + 3}")
print(f"Upper: {model.upper()}")
Don't use .format() or % formatting
Older Python code uses "Hello {}".format(name) or "Hello %s" % name. F-strings (f"Hello {name}") are cleaner, faster, and the modern standard. Only use the older styles if you need to support Python 3.5 or earlier.
Numbers (int & float)
# Integers โ whole numbers
count = 42
negative = -10
big = 1_000_000 # underscores for readability
# Floats โ decimal numbers
price = 19.99
scientific = 1.5e10 # 15000000000.0
# Arithmetic operators
print(10 + 3) # 13 addition
print(10 - 3) # 7 subtraction
print(10 * 3) # 30 multiplication
print(10 / 3) # 3.33 division (always returns float)
print(10 // 3) # 3 floor division (integer result)
print(10 % 3) # 1 modulo (remainder)
print(2 ** 3) # 8 exponentiation
# Comparison operators (return bool)
print(5 == 5) # True equal
print(5 != 3) # True not equal
print(5 > 3) # True greater than
print(5 3) # True less than
print(5 >= 5) # True greater or equal
# Float gotcha!
print(0.1 + 0.2 == 0.3) # False! (floating point precision)
print(0.1 + 0.2) # 0.30000000000000004
Why does 0.1 + 0.2 โ 0.3?
This isn't a Python bug โ it's how all computers store decimal numbers (IEEE 754). For AI work, you rarely need exact decimal equality. If you do, use the decimal module or round().
Booleans (bool)
# Only two values: True and False (capital first letter!)
is_running = True
is_stopped = False
# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # False
# Truthy and Falsy โ these values are "falsy":
# False, None, 0, 0.0, "", [], {}, set()
print(bool(0)) # False
print(bool("")) # False
print(bool("hello")) # True (non-empty string)
print(bool(42)) # True (non-zero number)
# Practical: check if a variable has a value
result = get_api_response() # might return None
if result: # truthy check
print("Got a response!")
Type Conversion
You'll frequently convert between types โ especially when parsing user input or API responses.
# String to number
age_str = "28"
age = int(age_str) # 28
price = float("19.99") # 19.99
# Number to string
count_str = str(42) # "42"
# To boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
# Common AI pattern: parsing API responses
api_response = "1500" # API returns string
tokens = int(api_response) # Convert to int for math
cost = tokens * 0.000015 # Calculate cost
print(f"Cost: ${cost:.4f}")
# ERROR: Can't convert non-numeric string
# int("hello") โ ValueError!
None โ The "Nothing" Value
# None represents "no value" or "not set yet"
result = None
# Always check for None with 'is', not '=='
if result is None:
print("No result yet")
# Common pattern: optional function return
def find_user(user_id):
# ... database lookup ...
if not found:
return None
return user_data
# Dangerous: check None, not just truthy
# 0, "", False are falsy but NOT None
๐งช Exercises
Exercise 1 โ Variable Swap
Create two variables a = "left" and b = "right". Swap their values without using a third variable. (Hint: Python tuple unpacking.)
Exercise 2 โ Token Cost Calculator
Given: prompt_tokens = 500, completion_tokens = 1500, price_per_1k_input = 0.005, price_per_1k_output = 0.015. Calculate and print the total cost formatted as "Total cost: $0.0250" using f-strings.
Exercise 3 โ Type Detector
Write a script that takes any variable and prints its type and value. Test with 42, 3.14, "hello", True, None, and [1, 2, 3].
โ ๏ธ Common Mistakes
Using = instead of == for comparison
x = 5 assigns 5 to x. x == 5 checks if x equals 5. Mixing these up causes bugs that are hard to catch.
Not converting types from input()
input() always returns a string. If you ask for a number, you must convert: age = int(input("Age? ")). Otherwise "25" + 5 raises TypeError.
Checking None with ==
Use if x is None, not if x == None. The is check is the Python convention and avoids edge cases with custom classes.