AI Engineering from Scratch
Introduction to Programming
Giving the Computer Instructions
Programming is how we communicate with computers. Just like we use languages like English or Spanish to talk to each other, we use programming languages to give computers instructions. The computer follows these instructions precisely to perform a task, whether it's calculating a budget, playing a video, or powering an AI.
We'll be using Python, a language known for its readability. Its syntax—the rules for how code is written and structured—is clean and straightforward, making it a great starting point. The goal is to write instructions that are not only correct but also make sense to other humans who might read them later.
Storing and Labeling Information
To do anything useful, a program needs to work with information, or data. We store this data in variables, which are like labeled boxes where we can keep values. When we need to use the value, we just refer to the box's label.
Data comes in different forms, called data types. Python automatically recognizes the type of data you're storing. Here are the most common ones:
| Data Type | Description | Example |
|---|---|---|
int | Integer, for whole numbers. | age = 30 |
float | Floating-point number, for decimals. | price = 19.99 |
str | String, for text. Always in quotes. | name = "Alice" |
bool | Boolean, for true or false values. | is_student = True |
Let's see this in action. The equals sign (=) is the assignment operator; it tells the computer to put the value on the right into the variable on the left.
# Assigning values to variables
user_age = 25 # An integer
account_balance = 150.75 # A float
user_name = "Bob" # A string
is_active = False # A boolean
# We can print the value of a variable to see it
print(user_name)
print(account_balance)
Making Decisions and Repeating Tasks
Programs often need to make decisions or repeat actions. This is handled by control structures. They direct the "flow" of the program, determining which lines of code get executed and in what order.
Conditionals let a program make choices. Using if, elif (else if), and else, you can run different blocks of code depending on whether a condition is true or false. Think of it like deciding whether to bring an umbrella: if it's raining, take one, else leave it at home.
temperature = 15
if temperature > 25:
print("It's a hot day!")
elif temperature > 10:
print("It's a pleasant day.")
else:
print("Better bring a jacket.")
Loops are for repetition. A for loop is great for when you want to repeat a task a specific number of times, like going through every item in a list.
# This loop will run 3 times
guests = ["Alice", "Bob", "Charlie"]
for guest in guests:
print(f"Welcome, {guest}!")
Creating Reusable Code
If you find yourself writing the same piece of code over and over, you can bundle it into a function. A function is a named, reusable block of code that performs a single, specific task. You give it a name, define the steps it should take, and then you can "call" it by name whenever you need it, just like using a tool from a toolbox.
This makes your code more organized, easier to read, and less prone to errors. If you need to update the logic, you only have to change it in one place: inside the function.
# Define a function to greet a user
def greet_user(name):
message = f"Hello, {name}! Welcome."
return message
# Call the function with different inputs
greeting_for_alice = greet_user("Alice")
greeting_for_bob = greet_user("Bob")
print(greeting_for_alice)
print(greeting_for_bob)
Related functions can be grouped together in files called modules. Python has a huge collection of pre-built modules that you can import to add powerful capabilities to your programs without having to write everything from scratch.
Handling Errors
No programmer is perfect, and errors, often called "bugs," are a natural part of the process. Sometimes a program might crash because of an unexpected input or a logical mistake. Python stops and displays an error message when this happens.
Instead of letting the program crash, we can anticipate potential problems and handle them gracefully using a try...except block. You put the code that might fail in the try block, and the code that should run if an error occurs goes in the except block.
This is a key part of writing robust programs that don't break easily.
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: You can't divide by zero!")
The process of finding and fixing these bugs is called debugging. It's a problem-solving skill every programmer develops over time, involving careful reading of error messages, testing code, and thinking critically about where things might have gone wrong.
Now, let's test your understanding of these core concepts.
What is the primary purpose of a programming language?
In programming, a variable is best described as a labeled container for storing data.
These building blocks—variables, control structures, and functions—are the foundation of almost every program you'll ever write or see. Mastering them is the first big step on your programming journey.
