No history yet

Python Basics

The Building Blocks

Programming is all about working with information. To do anything useful, we need a way to store and label that information. In Python, we use variables for this. A variable is like a labeled box where you can keep a piece of data.

variable

noun

A name that refers to a value stored in the computer's memory.

Assigning a value to a variable is simple:

# A variable named 'company_name' holds the text 'Global Tech Inc.'
company_name = "Global Tech Inc."

# A variable named 'stock_price' holds the number 150.75
stock_price = 150.75

# A variable named 'shares_outstanding' holds the integer 5000000
shares_outstanding = 5000000

The type of data a variable holds is important. Python automatically understands different data types, but knowing them helps you understand what you can do with your data.

  • Strings: Text, like a company name. You create them with quotes. "Hello" or 'Report.pdf'.
  • Integers: Whole numbers, like the number of shares. 10, -5, 2024.
  • Floats: Numbers with a decimal point, like a stock price. 99.95, 0.01.
  • Booleans: Can only be one of two values: True or False. They are perfect for answering yes-or-no questions.
# An example of a boolean
is_profitable = True

Making Decisions and Repeating Actions

A program's real power comes from its ability to make decisions and perform repetitive tasks. This is handled by control structures.

To make decisions, you use if, elif (short for "else if"), and else. The code inside an if block only runs if its condition is True.

revenue = 1000000
costs = 850000

if revenue > costs:
    print("The company is profitable.")
else:
    print("The company is not profitable.")

For repetitive tasks, loops are essential. A for loop is great for when you want to do something for each item in a list.

# A list of stock tickers
stock_tickers = ['AAPL', 'GOOG', 'MSFT']

# Loop through each ticker and print it
for ticker in stock_tickers:
    print(f"Processing data for {ticker}")

A while loop is used when you want to repeat an action as long as a certain condition remains true. For example, you might process lines from a file until you run out of lines.

# A simple countdown
counter = 5

while counter > 0:
    print(counter)
    counter = counter - 1 # Decrease the counter by 1

print("Liftoff!")

Creating Reusable Code

Sometimes you need to perform the same set of actions over and over again. Instead of rewriting the same code, you can package it into a function. A function is a named, reusable block of code that performs a specific task.

You define a function using the def keyword. Functions can take inputs, called arguments, and can return an output.

# This function calculates the market capitalization
def calculate_market_cap(stock_price, shares_outstanding):
    market_cap = stock_price * shares_outstanding
    return market_cap

# Now we can use our function
goog_shares = 275000000
goog_price = 177.85
goog_market_cap = calculate_market_cap(goog_price, goog_shares)

print(f"Google's Market Cap: 💲{goog_market_cap}")

Using functions makes your code cleaner, easier to read, and less prone to errors. If you need to update the logic, you only have to change it in one place.

Working with Files

Often, the data you need to work with is stored in files. Python has simple, built-in tools for reading from and writing to files.

The best way to open a file is using a with statement. This ensures the file is automatically closed when you're done with it, even if errors occur.

Here's how you can read the contents of a text file line by line:

# Assume we have a file named 'expenses.txt'
# with each expense on a new line.

# Open the file for reading ('r')
with open('expenses.txt', 'r') as file:
    for line in file:
        # .strip() removes any extra whitespace or newline characters
        print(line.strip())

Writing to a file is just as straightforward. If the file doesn't exist, Python will create it for you. Be careful: opening a file in write mode ('w') will overwrite its existing contents.

# A list of quarterly revenues
revenues = [
    'Q1: 💲120,000',
    'Q2: 💲150,000',
    'Q3: 💲135,000',
    'Q4: 💲165,000'
]

# Open a file for writing ('w')
with open('revenue_report.txt', 'w') as file:
    file.write('Annual Revenue Report\n') # \n is a newline character
    file.write('---------------------\n')
    for r in revenues:
        file.write(r + '\n')

This creates a new file called revenue_report.txt with a simple report inside. These basic file operations are the first step toward handling more complex data sources, like PDFs.

Time to review the key terms we've covered.

Let's check your understanding of these fundamental concepts.

Quiz Questions 1/6

In Python, what is the data type of the value assigned to price in the following statement?

price = 129.99
Quiz Questions 2/6

What is the primary purpose of defining a function in a program?

With variables, control structures, functions, and file handling, you have the core tools to start writing useful Python programs for processing data.