Python for Data Analysis
Python Basics
The Building Blocks of Python
Think of Python code as a set of instructions for your computer. Like any language, it has rules about grammar and structure. This is its syntax. Luckily, Python's syntax is known for being clean and readable, which makes it a great language for beginners.
At the core of almost any program are variables. A variable is just a name you give to a piece of data so you can refer to it later. It’s like putting a label on a box. You use the equals sign () to assign a value to a variable.
# Assigning a value to a variable
message = "Hello, world!"
# Printing the value of the variable
print(message)
In this example, message is the variable name, and it holds the text "Hello, world!". The print() command is a built-in Python function that displays the value of whatever is inside the parentheses.
Data Types
Variables can hold different kinds of data. Python has several built-in data types, but let's focus on the most common ones you'll encounter in data analysis.
| Data Type | Description | Example |
|---|---|---|
String (str) | A sequence of characters, like text. | "Hello", 'Python' |
Integer (int) | A whole number, without a decimal. | 10, -5, 2024 |
Float (float) | A number with a decimal point. | 3.14, -0.5, 100.0 |
Boolean (bool) | Represents one of two values: True or False. | True, False |
Beyond these simple types, you'll also work with collections of data. The two most fundamental are lists and dictionaries.
- Lists: An ordered collection of items, enclosed in square brackets
[]. Lists are changeable, meaning you can add, remove, or alter items. - Dictionaries: An unordered collection of key-value pairs, enclosed in curly braces
{}. Each item has a uniquekeythat points to avalue.
# A list of numbers
scores = [88, 92, 77, 95, 84]
# A dictionary of a student's information
student = {
"name": "Alice",
"id": 12345,
"major": "Data Science"
}
Making Decisions and Repeating Actions
Programs often need to make decisions based on certain conditions. This is where control structures come in. The if statement runs a block of code only if a condition is true.
temperature = 75
if temperature > 70:
print("It's a warm day!")
You can add an else statement to run code if the condition is false, and elif (short for "else if") to check for multiple conditions in sequence.
temperature = 50
if temperature > 70:
print("It's warm.")
elif temperature > 40:
print("It's cool.")
else:
print("It's cold.")
# Output: It's cool.
What if you need to perform the same action multiple times? That's what loops are for. A for loop is great for iterating over a sequence, like a list.
# Print each score from the list
scores = [88, 92, 77]
for score in scores:
print(score)
A while loop repeats as long as a certain condition remains true. It's useful when you don't know in advance how many times you need to loop.
count = 1
while count <= 3:
print(f"The count is {count}")
count = count + 1 # Increment the count
# Output:
# The count is 1
# The count is 2
# The count is 3
Reusable Code with Functions
As your programs get more complex, you'll find yourself writing the same bits of code over and over. Functions let you package up a block of code, give it a name, and reuse it whenever you need it. This principle is called DRY (Don't Repeat Yourself).
You define a function using the def keyword. Functions can take inputs, called arguments or parameters, and can produce an output using the return keyword.
# Define a function to calculate the average of a list of numbers
def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return average
# Use the function
scores = [88, 92, 77, 95, 84]
average_score = calculate_average(scores)
print(f"The average score is: {average_score}")
# Output: The average score is: 87.2
Here, calculate_average is the function name, and numbers is its parameter. When we call the function with our scores list, it calculates the average and returns the result, which we then store in the average_score variable.
Handling Errors
Sometimes, code doesn't work as expected. You might try to divide a number by zero or access an item in a list that doesn't exist. These situations raise errors, or exceptions, which can crash your program.
To prevent this, you can anticipate potential errors and handle them gracefully using a try...except block. Python will try to run the code in the try block. If an error occurs, it will skip to the except block instead of crashing.
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: You can't divide by zero!")
# Output: Error: You can't divide by zero!
By catching the ZeroDivisionError, our program informs us of the problem and continues running. This is crucial for writing robust code that can handle unexpected inputs or situations.
In Python, which symbol is used to assign a value to a variable?
Which of the following creates an ordered, changeable collection of items?
These are the fundamental building blocks of Python. Mastering variables, data types, control structures, functions, and error handling will give you a solid foundation for tackling any data analysis task.