Learning the Building Blocks

Every programming language shares core concepts. Learn them once, and you can apply them anywhere.

This chapter covers the fundamentals using Python, with AI as your tutor. For each concept, you'll:

  1. See a brief introduction
  2. Get prompts to explore with AI
  3. Practice with exercises
  4. Build understanding through doing

Let's start.

Variables: Storing Information

Variables store data that your program uses. Think of them as labeled boxes that hold values.

The Basics

# Creating variables
name = "Alice"
age = 25
height = 5.6
is_student = True

# Using variables
print(name)        # Output: Alice
print(age)         # Output: 25

AI Learning Prompt

I'm learning about variables in Python.

Explain:
1. What variables are (simple analogy)
2. How to create them
3. Rules for naming variables
4. What happens when you reassign a variable

Then give me 3 simple exercises to practice, starting very easy.

Practice Exercises

Try these yourself before asking AI for answers:

  1. Create variables for your name, age, and favorite color. Print each one.
  2. Create a variable called score with value 100. Then change it to 85. Print it after each assignment.
  3. Try creating a variable called my-name (with a hyphen). What happens?

Checking Your Understanding

I completed the variable exercises. Here's what I wrote:

[Paste your code]

Did I do these correctly? What could I improve?

Data Types: Different Kinds of Data

Not all data is the same. Numbers behave differently than text. Python has several data types.

The Basics

# Strings (text)
greeting = "Hello"
name = 'World'      # Single or double quotes work

# Integers (whole numbers)
count = 42
negative = -10

# Floats (decimal numbers)
price = 19.99
pi = 3.14159

# Booleans (True/False)
is_active = True
is_empty = False

# Checking types
print(type(greeting))  # <class 'str'>
print(type(count))     # <class 'int'>

AI Learning Prompt

I'm learning about data types in Python.

Explain these types with examples:
- Strings
- Integers
- Floats  
- Booleans

Then explain:
- When to use each type
- How to convert between types (like string to integer)
- Common mistakes beginners make with types

Give me 3 exercises to practice.

Practice Exercises

  1. Create variables of each type (string, integer, float, boolean). Use type() to verify each one.
  2. Try adding a string and an integer ("5" + 3). What happens? Ask AI to explain the error.
  3. Convert the string "42" to an integer. Then multiply it by 2.

Operators: Doing Things with Data

Operators let you manipulate data — math, comparisons, and logic.

Math Operators

a = 10
b = 3

print(a + b)   # Addition: 13
print(a - b)   # Subtraction: 7
print(a * b)   # Multiplication: 30
print(a / b)   # Division: 3.333...
print(a // b)  # Integer division: 3
print(a % b)   # Modulo (remainder): 1
print(a ** b)  # Power: 1000

Comparison Operators

x = 5
y = 10

print(x == y)   # Equal: False
print(x != y)   # Not equal: True
print(x < y)    # Less than: True
print(x > y)    # Greater than: False
print(x <= y)   # Less or equal: True
print(x >= y)   # Greater or equal: False

Logical Operators

a = True
b = False

print(a and b)  # Both true? False
print(a or b)   # Either true? True
print(not a)    # Opposite: False

AI Learning Prompt

I learned about operators in Python. Quiz me on them.

Give me 10 quick questions like:
"What does 17 % 5 equal?"
"What does (5 > 3) and (2 > 8) equal?"

After I answer, tell me which I got right and explain any I missed.

Practice Exercises

  1. Calculate the area of a rectangle (width=7, height=4) using variables and operators.
  2. Check if a number is even using the modulo operator (%).
  3. Write a comparison that checks if age is between 18 and 65 (inclusive).

Conditionals: Making Decisions

Programs need to make decisions. Conditionals let code choose different paths.

The Basics

age = 20

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# Multiple conditions
score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")

Important: Indentation

Python uses indentation (spaces) to define code blocks. This matters:

# Correct
if True:
    print("This is inside the if")
print("This is outside")

# Wrong - will error
if True:
print("This will break")  # Missing indentation!

AI Learning Prompt

I'm learning about if/elif/else in Python.

Explain:
1. How conditionals work
2. Why indentation matters
3. When to use elif vs multiple if statements
4. Common mistakes with conditionals

Then give me a problem to solve:
"Write a program that takes a temperature and prints whether it's hot (>80), warm (60-80), or cold (<60)"

Let me try it first, then I'll show you my solution.

Practice Exercises

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Write a program that determines if someone can vote (age >= 18) and is registered (is_registered = True).
  3. Write a simple grading program: A (90+), B (80-89), C (70-79), D (60-69), F (below 60).

Loops: Repeating Actions

Loops run code multiple times. Essential for processing lists, automating tasks, and more.

For Loops

# Loop through a range
for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Loop with range(start, stop)
for i in range(1, 6):
    print(i)  # Prints 1, 2, 3, 4, 5

While Loops

# Loop while condition is true
count = 0
while count < 5:
    print(count)
    count += 1  # Important: change the condition!

# Be careful of infinite loops!
# This would run forever:
# while True:
#     print("Help!")

AI Learning Prompt

I'm learning about loops in Python.

Explain:
1. Difference between for and while loops
2. When to use each type
3. How to avoid infinite loops
4. How break and continue work

Give me 3 loop exercises, starting easy.

Practice Exercises

  1. Print the numbers 1-10 using a for loop.
  2. Print the numbers 10 down to 1 using a while loop.
  3. Loop through a list of names and print "Hello, [name]!" for each.

Functions: Reusable Code

Functions are reusable blocks of code. Instead of repeating yourself, write a function once and call it many times.

The Basics

# Defining a function
def greet(name):
    print(f"Hello, {name}!")

# Calling a function
greet("Alice")  # Output: Hello, Alice!
greet("Bob")    # Output: Hello, Bob!

# Function with return value
def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # Output: 8

# Function with default parameter
def greet(name="World"):
    print(f"Hello, {name}!")

greet()         # Output: Hello, World!
greet("Alice")  # Output: Hello, Alice!

AI Learning Prompt

I'm learning about functions in Python.

Explain:
1. Why functions are useful
2. The difference between parameters and arguments
3. What "return" does
4. Scope - why variables inside functions don't leak out

Walk me through creating a function that:
- Takes two numbers
- Returns the larger one

Let me try writing it first.

Practice Exercises

  1. Write a function called square that takes a number and returns its square.
  2. Write a function called is_even that returns True if a number is even, False otherwise.
  3. Write a function called count_vowels that counts vowels in a string.

Lists: Collections of Data

Lists store multiple items in a single variable.

The Basics

# Creating lists
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []

# Accessing elements (index starts at 0)
print(numbers[0])   # 1
print(numbers[-1])  # 5 (last element)

# Modifying lists
numbers.append(6)       # Add to end
numbers.insert(0, 0)    # Insert at position
numbers.remove(3)       # Remove specific value
popped = numbers.pop()  # Remove and return last

# List length
print(len(numbers))

# Looping through lists
for num in numbers:
    print(num)

AI Learning Prompt

I'm learning about lists in Python.

Explain:
1. How indexing works (including negative indexes)
2. Common list methods (append, insert, remove, pop, sort)
3. List slicing
4. The difference between lists and strings

Give me practice problems involving:
- Creating lists
- Accessing elements
- Modifying lists
- Looping through lists

Practice Exercises

  1. Create a list of your 5 favorite foods. Print the first and last items.
  2. Write a function that takes a list of numbers and returns the sum.
  3. Write a function that takes a list and returns a new list with only the even numbers.

Dictionaries: Key-Value Pairs

Dictionaries store data as key-value pairs. Like a real dictionary: look up a word (key), get a definition (value).

The Basics

# Creating a dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Accessing values
print(person["name"])       # Alice
print(person.get("age"))    # 30
print(person.get("job", "Unknown"))  # Unknown (default)

# Modifying
person["age"] = 31          # Update
person["job"] = "Engineer"  # Add new

# Looping
for key in person:
    print(f"{key}: {person[key]}")

# Or
for key, value in person.items():
    print(f"{key}: {value}")

AI Learning Prompt

I'm learning about dictionaries in Python.

Explain:
1. When to use dictionaries vs lists
2. How to access, add, and modify entries
3. What happens if I access a key that doesn't exist
4. Common dictionary methods

Give me a problem:
Create a simple contact book that stores names and phone numbers.

Practice Exercises

  1. Create a dictionary representing a book (title, author, year, pages).
  2. Write a function that takes a dictionary and prints each key-value pair nicely formatted.
  3. Create a word frequency counter: given a list of words, return a dictionary with each word and its count.

Putting It Together

These fundamentals combine to create real programs. Here's a mini-project:

Simple Quiz Game

def run_quiz():
    score = 0
    questions = [
        {"question": "What is 2 + 2?", "answer": "4"},
        {"question": "What is the capital of France?", "answer": "Paris"},
        {"question": "What color is the sky?", "answer": "Blue"}
    ]
    
    for q in questions:
        user_answer = input(q["question"] + " ")
        if user_answer.lower() == q["answer"].lower():
            print("Correct!")
            score += 1
        else:
            print(f"Wrong. The answer is {q['answer']}")
    
    print(f"\nYou got {score}/{len(questions)} correct!")

run_quiz()

Try understanding this code. Then ask AI:

Here's a quiz game program I'm studying:

[Paste the code]

Walk me through how it works, line by line. Then suggest one improvement I could make.

What's Next

You now know the building blocks: variables, types, operators, conditionals, loops, functions, lists, and dictionaries.

But knowing concepts and applying them are different. When your code doesn't work, you need debugging skills.

Chapter 4 covers debugging and problem-solving with AI — turning errors from frustrating obstacles into learning opportunities.