No history yet

Introduction to Programming

The Building Blocks of Code

At its heart, programming is about telling a computer what to do. To give these instructions, we need a way to store and label information. This is where variables come in. Think of a variable as a labeled box where you can keep a piece of information. You give the box a name, and you can put something inside it. Later, you can refer to the box by its name to see what's inside or even change its contents.

# company_name is the variable, 'Innovate Inc.' is the value
company_name = 'Innovate Inc.'

# Other examples of variables
founding_year = 2021
current_valuation = 75.5  # In millions
is_profitable = True

The information we store in variables comes in different forms, known as data types. The examples above show the most common ones:

  • Strings: Text, like 'Innovate Inc.'. You can spot them because they are wrapped in quotes.
  • Integers: Whole numbers, like 2021.
  • Floats: Numbers with a decimal point, like 75.5.
  • Booleans: Can only be one of two values, True or False. They are perfect for tracking yes-or-no conditions.

variable

noun

A named storage location in a computer's memory that holds a value. The value can be changed during program execution.

Understanding data types is crucial because they determine what you can do with a variable. You can perform math with integers and floats, but you can't multiply two company names together. Python is smart about types, but knowing the difference helps you write code that works as expected.

Making Decisions and Repeating Tasks

Programs rarely run in a straight line from top to bottom. They need to make decisions and perform repetitive actions. This is handled by control structures. The most common decision-making tool is the if statement. It lets your code execute a certain block only if a specific condition is true.

Imagine you're analyzing a startup. You might only want to investigate further if its annual recurring revenue (ARR) is above a certain threshold. An if statement is perfect for this.

annual_revenue = 1200000  # 💲1.2 million

if annual_revenue > 1000000:
    print('This company meets the revenue threshold.')
elif annual_revenue > 500000:
    print('This company is worth a closer look.')
else:
    print('Too early for our fund.')

Here, the code checks the annual_revenue. Since it's greater than 1,000,000, it prints the first message. elif (short for 'else if') lets you check another condition, and else provides a default action if none of the preceding conditions are met.

Now, what if you need to perform the same action on a list of items? You could write the same code over and over, but that's inefficient. Instead, we use loops. A for loop is ideal when you want to iterate over every item in a sequence, like a list of companies.

portfolio_companies = ['Innovate Inc.', 'DataDrive', 'NextGen AI']

for company in portfolio_companies:
    print(f'Analyzing {company}...')
    # Imagine more complex analysis code here

This loop takes each company name from the list one by one, assigns it to the company variable, and runs the indented code. Once it's gone through every item, the loop stops. It's a powerful way to automate repetitive analysis.

Packaging and Reusing Code

As your programs grow, you'll find yourself writing the same chunks of code repeatedly. A better approach is to package that code into a function. A function is a named, reusable block of code that performs a specific task. You define it once and can then 'call' it whenever you need it, often providing it with some input to work on.

For example, instead of writing the same calculation for a company's 'Rule of 40' score every time, you can put it in a function.

function

noun

A block of organized, reusable code that is used to perform a single, related action.

# Define the function
def calculate_rule_of_40(growth_rate, profit_margin):
    score = growth_rate + profit_margin
    return score

# Call the function with specific data
company_a_score = calculate_rule_of_40(0.30, 0.15) # 30% growth, 15% margin
print(f'Company A score: {company_a_score}') # Prints 0.45

The function takes growth_rate and profit_margin as inputs (called parameters), calculates the score, and then uses return to send the result back. This makes your code cleaner, easier to read, and less prone to errors.

Python also has a vast collection of pre-written code organized into modules. A module is simply a file containing Python definitions and statements. To use code from a module, you import it. This gives you access to powerful tools without having to write them from scratch. For data analysis, you'll frequently use modules like pandas for data manipulation and matplotlib for plotting.

# Import the 'math' module to access advanced math functions
import math

# Now you can use functions from the math module
value = 100
square_root = math.sqrt(value)
print(f'The square root of {value} is {square_root}.')

Handling the Unexpected

No one writes perfect code on the first try. Errors, often called 'bugs' or 'exceptions,' will happen. Maybe you try to divide a number by zero, or reference a variable that doesn't exist. When Python encounters an error, it will stop and display a message explaining what went wrong.

Learning to read these error messages is a key skill in debugging, which is the process of finding and fixing errors in your code.

Sometimes, you can anticipate that a certain block of code might fail. For instance, you might be processing a file that doesn't exist. Instead of letting the program crash, you can handle the error gracefully using a try...except block.

company_data = {'name': 'Innovate Inc.', 'revenue': 5000000}

try:
    # This line will cause a KeyError because 'profit' is not in the dictionary
    profit = company_data['profit']
    print(f'Profit is: {profit}')
except KeyError:
    # This block runs only if a KeyError occurs in the 'try' block
    print('Profit data is not available for this company.')

In this example, the code in the try block attempts to access a key that doesn't exist. Instead of crashing, Python jumps to the except KeyError block and executes that code. This allows your program to continue running even when it encounters predictable problems.

Quiz Questions 1/6

What is the primary role of a variable in programming?

Quiz Questions 2/6

Which data type would you use to store a company's name, such as 'Innovate Inc.'?

These are the fundamental concepts that form the basis of nearly every computer program. By understanding variables, control structures, functions, and error handling, you have the tools to start writing simple but powerful scripts to automate your work.