Python for Data Analysis
Python Basics
Storing Your Ingredients
Think of programming like cooking. Before you can make a meal, you need ingredients. In Python, your ingredients are data, and you store them in variables. A variable is just a container with a label. You give it a name and put some information inside.
# Assign the value 10 to a variable named 'apples'
apples = 10
# Assign the text "Hello" to a variable named 'greeting'
greeting = "Hello"
print(apples)
print(greeting)
Just like in a kitchen, your ingredients come in different types. You wouldn't store soup in a spice rack. Python needs to know what kind of data it's working with. The most common types are:
- Integers: Whole numbers, like 5, -20, or 0.
- Floats: Numbers with a decimal point, like 3.14 or -0.5.
- Strings: Plain text, wrapped in quotes. "Hello world!" is a string.
- Booleans: Can only be one of two values:
TrueorFalse. They're like a light switch, either on or off.
These basic types are the building blocks for all data analysis. You'll use them to represent everything from sales counts and prices to customer names and survey responses.
If you're ever unsure what type of data is in a variable, you can ask Python using the type() function.
price = 19.99
is_in_stock = True
print(type(price))
print(type(is_in_stock))
Following the Recipe
A program, like a recipe, is a set of instructions. But sometimes, you need to make decisions or repeat steps. This is called control flow.
To make a decision, you use an if statement. It checks if a condition is true and runs a block of code only if it is. You can add elif (else if) for more options and else for a default action.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("Better bring a jacket.")
else:
print("The weather is perfect.")
What if you need to do something over and over? That's where loops come in. A for loop is perfect for repeating an action for every item in a list.
# A list of expenses
expenses = [12.50, 45.00, 8.75]
total = 0
for expense in expenses:
total = total + expense
print(f"Total expenses: 💲{total}")
Another type is the while loop. It keeps running as long as its condition is true. Be careful with these, as they can run forever if the condition never becomes false!
count = 5
while count > 0:
print(count)
count = count - 1
print("Blast off!")
Organizing Your Kitchen
Imagine writing down the instructions for making a sandwich every single time you wanted one. It would be tedious. A better way is to write one recipe called "Make Sandwich" and just refer to it whenever you're hungry.
In Python, these reusable recipes are called functions. You define a block of code, give it a name, and then you can run it anytime just by calling its name. This keeps your code clean and easy to manage.
# Define a function to calculate sales tax
def calculate_tax(price):
tax_rate = 0.07
return price * tax_rate
# Use the function
item_price = 150
tax_amount = calculate_tax(item_price)
print(f"The tax is: 💲{tax_amount}")
Sometimes, you need special tools that aren't built into Python by default. These tools are stored in modules. A module is a file containing a collection of related functions. To use them, you just import the module.
For example, the math module gives you access to more advanced mathematical functions.
# Import the math module to get access to its functions
import math
# Now we can use the square root function
number = 81
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}")
Handling Spills
Even the best chefs spill something now and then. In programming, errors happen. Your program might try to divide by zero, or a user might enter text where a number is expected. When this happens, Python raises an error, or exception, and the program crashes.
To prevent this, you can anticipate problems 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 stopping.
user_input = "abc"
try:
# This will cause an error because "abc" is not a number
number = int(user_input)
print(f"Your number is {number}")
except ValueError:
# This code runs if a ValueError occurs
print("That wasn't a valid number! Please try again.")
This makes your code more robust and user-friendly. Instead of a confusing error message, the user gets a helpful instruction.
With these fundamentals of variables, control structures, functions, and error handling, you have the core toolkit to start writing powerful scripts for data analysis.
In Python, if you have the line of code x = "25.5", what is the data type of the value stored in the variable x?
What is the primary purpose of a try...except block in Python?