Python for Data Analysis
Python Basics
Storing Your Data
Think of a variable as a labeled box where you can store information. You give the box a name, and you can put something inside it. In Python, you can change what's inside the box whenever you want.
project_name = "Mars Rover"
print(project_name) # This will display "Mars Rover"
The kind of information you store determines its data type. For data analysis, you'll mainly work with a few core types:
- Strings: Text, like a name or a description. You write them inside quotes (
"or'). - Integers: Whole numbers, like 42 or -100.
- Floats: Numbers with a decimal point, like 3.14 or 99.9.
- Booleans: Can only be
TrueorFalse. They're great for asking yes-or-no questions.
# Examples of different data types
mission_name = "Apollo 11" # A string
crew_size = 3 # An integer
lunar_gravity = 1.62 # A float
mission_success = True # A boolean
Often, you'll need to work with a collection of items. A Python list is perfect for this. It’s an ordered collection of items, stored in a single variable.
planets = ["Mercury", "Venus", "Earth", "Mars"]
# You can access items by their position (index), starting from 0
print(planets[2]) # This will display "Earth"
Making Decisions and Repeating Tasks
Your code often needs to make decisions. This is done with control structures. The most common is the if statement, which runs code only if a certain condition is true. You can add elif (else if) for more options and else as a catch-all.
temperature = 15
if temperature > 25:
print("It's hot outside.")
elif temperature > 10:
print("It's a pleasant day.")
else:
print("You might need a jacket.")
What if you need to do the same thing over and over? That's where loops come in. A for loop is great for going through each item in a list.
planets = ["Mercury", "Venus", "Earth", "Mars"]
for planet in planets:
print("Checking status of: " + planet)
Another type of loop is the while loop. It keeps running as long as a condition is true. Be careful with these, as they can run forever if the condition never becomes false!
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1 # This is crucial to avoid an infinite loop
print("Liftoff!")
Creating Reusable Code
When you find yourself writing the same bit of code multiple times, it’s time to create a function. A function is a named, reusable block of code that performs a specific task. Think of it like a recipe: you give it some ingredients (called arguments or parameters), and it gives you back a finished dish (a return value).
# This function calculates the area of a rectangle
def calculate_area(length, width):
area = length * width
return area
Once defined, you can call the function as many times as you like with different inputs.
room1_area = calculate_area(10, 5)
room2_area = calculate_area(8.5, 6.2)
print("Area of room 1 is:", room1_area)
print("Area of room 2 is:", room2_area)
Handling the Unexpected
Sometimes, code doesn't work as planned. An operation might be impossible, like dividing a number by zero or trying to open a file that doesn’t exist. These situations cause errors, which can crash your program.
To prevent this, you can use a try...except block. Python will try to run the code in the try block. If an error occurs, it jumps to the except block and runs that code instead of crashing.
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: You can't divide by zero!")
print("The program continues after the error.")
This lets you handle potential problems gracefully without stopping the entire script. It's a key part of writing robust code that can deal with messy, real-world data.
What is the data type of the variable price in the following Python code?
price = 99.9
Which of the following describes a Python list?