Python for Excel Users
Python Basics
From Cells to Variables
In Excel, you store data in cells like A1 or B2. In Python, you use variables. A variable is just a name you give to a piece of data so you can refer to it later. It's like giving a cell a name like total_sales instead of calling it C20.
Assigning a value to a variable is simple.
total_sales = 500
customer_name = "Acme Corp"
Just as Excel has different types of data (text, numbers, dates), Python does too. The most common ones are:
- Strings: Text, which you wrap in quotes. Example:
"Hello, world!" - Integers: Whole numbers. Example:
2024 - Floats: Numbers with decimals. Example:
19.99 - Booleans: Can only be
TrueorFalse. This is just likeTRUEandFALSEin Excel formulas.
Python automatically figures out the data type when you assign a value.
Variable
noun
A named storage location in memory that holds a value. You can change the value stored in a variable at any time.
Making Decisions and Repeating Actions
You already use logic in Excel with the IF function. Python's if statement is similar but more flexible. It lets you run a block of code only when a certain condition is True.
temperature = 15
if temperature > 25:
print("It's a hot day!")
elif temperature > 10:
print("It's a pleasant day.")
else:
print("You should bring a jacket.")
# This will print: "It's a pleasant day."
The elif (else if) lets you check multiple conditions, and else runs if none of the previous conditions were met.
Repetitive tasks are handled with loops. Think of this like dragging a formula down a column to apply it to every row. A for loop iterates over a sequence of items, like a list of names or numbers.
expenses = [120, 34, 55, 80]
total = 0
for expense in expenses:
total = total + expense
print(total) # This will print: 289
In the code above, the loop takes each number from the
expenseslist one by one and adds it to thetotalvariable. The indentation is important; it tells Python which code belongs inside the loop.
Building Reusable Tools
If you've ever created a complex formula in Excel, you know it's a pain to write it over and over. Functions in Python solve this problem. A function is a named, reusable block of code that performs a specific task. It's like creating your own custom Excel function.
You define a function using def. It can take inputs (called parameters) and give back an output (a return value).
# Defines a function to calculate sales tax
def calculate_tax(price, tax_rate):
return price * tax_rate
# Uses the function
sales_tax = calculate_tax(150, 0.07)
print(sales_tax) # This will print: 10.5
Python also comes with many pre-built functions organized into modules. You can think of modules as Excel's library of built-in functions. To use them, you first have to import the module.
import math
# Use the sqrt function from the math module
root = math.sqrt(81)
print(root) # This will print: 9.0
Handling Mistakes Gracefully
In Excel, you sometimes see errors like #DIV/0! or #VALUE!. They tell you something went wrong with your formula. Python has a similar concept called exceptions. If your code tries to do something impossible, like dividing by zero or adding a number to a string of text, it will raise an exception and stop running.
To prevent your program from crashing, you can anticipate and handle these errors using a try...except block. This is like using Excel's IFERROR function to show a friendly message instead of an ugly error.
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
# This will print: "Error: Cannot divide by zero!"
The code inside the try block is executed first. If an error occurs, Python jumps to the except block and runs that code instead of crashing. If no error occurs, the except block is simply skipped.
Ready to check your understanding? Let's try a few questions.
In Python, what is a variable most similar to in an Excel context?
Which line of code correctly creates a variable holding a whole number?
These are the fundamental building blocks of Python. With variables, control structures, functions, and error handling, you have the tools to start writing powerful scripts.