No history yet

Programming Basics

The Building Blocks of Code

At its heart, programming is about telling a computer what to do with information. The most basic way we store that information is in a variable. Think of a variable as a labeled box where you can keep a piece of data. You give the box a name, and you put something inside it.

Variable

noun

A storage location in a computer's memory, paired with an associated symbolic name, which contains some known or unknown quantity of information referred to as a value.

The type of data you put in the box matters. A computer treats a number differently from a word. These categories are called data types.

  • Integer: A whole number, like 10, -5, or 2024.
  • Float: A number with a decimal point, like 3.14 or -0.5.
  • String: Text, enclosed in quotes. For example, "hello world".
  • Boolean: Represents truth values, either True or False. It’s the computer’s way of saying yes or no.
# Python code showing different data types

# An integer
user_age = 30

# A float
pi_value = 3.14159

# A string
user_name = "Alex"

# A boolean
is_active = True

Making Decisions and Repeating Actions

Once you have data, you need to do things with it. Control structures let you direct the flow of your program. The most common way to make a choice is with an if statement. It checks if a condition is true and runs a block of code only if it is.

An if statement is like a fork in the road. If a certain condition is met, the program goes one way; otherwise, it might go another way or continue straight on.

temperature = 75

if temperature > 80:
    print("It's hot outside!")
elif temperature < 60:
    print("You might need a jacket.")
else:
    print("The weather is pleasant.")

Sometimes you need to repeat an action. That's where loops come in. A for loop runs a block of code for each item in a sequence. A while loop runs as long as a certain condition remains true.

# A for loop that prints numbers 0 through 4
for i in range(5):
    print(i)

# A while loop that counts down from 3
count = 3
while count > 0:
    print(f"Countdown: {count}")
    count = count - 1 # This is crucial to avoid an infinite loop!
print("Liftoff!")

Packaging Your Code

As your programs get bigger, you'll find yourself writing the same lines of code over and over. A function is a reusable block of code that performs a specific task. You define it once and can then call it whenever you need it.

Think of it like a recipe. You write down the instructions for baking a cake once. Then, anytime you want a cake, you just follow the recipe instead of figuring it out from scratch. The ingredients are the function's inputs (called parameters), and the finished cake is the output (the return value).

# Define a function to greet a user
def greet(name):
    """This function takes a name as input and returns a greeting."""
    return f"Hello, {name}!"

# Call the function with different inputs
print(greet("Alice"))
print(greet("Bob"))

Using functions makes your code modular and easier to read. It also helps you follow the DRY principle: Don't Repeat Yourself.

Organizing Collections of Data

Often, you'll need to work with groups of data, not just single values. A list (sometimes called an array in other languages) is an ordered collection of items. It's like a shopping list where each item has a specific position.

In programming, we usually start counting from zero. So, the first item in a list is at index 0, the second is at index 1, and so on. You can access, add, and remove items from a list, making it a flexible way to handle collections of data.

# A list of scores
scores = [88, 92, 77, 95, 84]

# Access the first score (at index 0)
first_score = scores[0]
print(f"The first score is: {first_score}")

# Add a new score to the end of the list
scores.append(99)
print(f"Updated scores: {scores}")

# Find out how many items are in the list
num_scores = len(scores)
print(f"There are {num_scores} scores in the list.")

These fundamental concepts—variables, data types, control structures, functions, and lists—form the backbone of almost every program you'll write, especially in machine learning where you are constantly manipulating and analyzing data.