โ† Roadmap ๐Ÿ Month 1: Python
0/10

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

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.

python variables.py
# 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: name and Name are different variables
  • Use snake_case (Python convention): api_key, not apiKey
  • 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).

python strings.py
# 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.

python fstrings.py
# 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)

python numbers.py
# 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)

python bools.py
# 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.

python conversion.py
# 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

python none_example.py
# 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.

โœ… You've completed this step when you can confirm: