Python for Data Analysis
Python Basics
Storing Information
Think of variables as labeled boxes where you can store information. You give a box a name (the variable name) and put something inside it (the value). In Python, you can create a variable and assign it a value using the equals sign =.
project_name = "Mars Rover"
year_launched = 2020
budget_in_millions = 2700.5
is_successful = True
The type of information you store determines the variable's data type. The examples above show four common types:
- Strings: Text, like
"Mars Rover". You can use single or double quotes. - Integers: Whole numbers, like
2020. - Floats: Numbers with a decimal point, like
2700.5. - Booleans: Can only be
TrueorFalse. They're great for tracking states.
Python is smart enough to figure out the data type on its own when you assign a value. You don't have to declare it beforehand.
If you're ever unsure about a variable's data type, you can use the built-in type() function to check.
print(type(project_name))
print(type(budget_in_millions))
Making Decisions and Repeating Actions
Programs rarely run straight from top to bottom. They need to make decisions and perform repetitive tasks. That's where control structures come in. They direct the flow of your code.
To make decisions, we use if, elif (short for "else if"), and else. This structure lets your program do different things based on whether a condition is true or false.
temperature = 15
if temperature > 25:
print("It's a hot day.")
elif temperature > 10:
print("It's a pleasant day.")
else:
print("It's cold, bring a jacket!")
For repetitive tasks, we use loops. A for loop is perfect for when you want to do something for each item in a list.
# Let's process a list of sensor readings
sensor_readings = [101, 105, 98, 103, 99]
for reading in sensor_readings:
processed_reading = reading - 100
print(f"Adjusted reading: {processed_reading}")
A while loop is used when you want to repeat an action as long as a certain condition remains true. It's useful when you don't know ahead of time how many times you'll need to loop.
# Countdown for a rocket launch
countdown = 5
while countdown > 0:
print(f"{countdown}...")
countdown = countdown - 1
print("Liftoff!")
Creating Reusable Code Blocks
As you write more code, you'll find yourself repeating the same lines over and over. Functions let you package a block of code, give it a name, and reuse it whenever you need. This makes your code cleaner, easier to read, and less prone to errors.
function
noun
A named sequence of statements that performs a computation. It can take inputs (arguments) and produce an output (return value).
You define a function using the def keyword. You can specify inputs, called parameters, inside the parentheses. The return keyword sends a value back when the function is finished.
# A function to convert temperature from Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius_temp):
fahrenheit = (celsius_temp * 9/5) + 32
return fahrenheit
Once defined, you can call the function by its name and provide values, called arguments, for its parameters. The function will execute its code and give you back the return value, which you can store in a variable.
boiling_point_c = 100
boiling_point_f = celsius_to_fahrenheit(boiling_point_c)
print(f"Water boils at {boiling_point_f} degrees Fahrenheit.")
Handling Mistakes Gracefully
Sometimes, code doesn't work as expected. You might try to divide by zero or access a file that doesn't exist. These situations cause errors, or exceptions, that can crash your program. Instead of letting that happen, you can anticipate and handle them.
Python's try...except block is the tool for this. You put the code that might cause an error in the try block. If an error occurs, the code in the except block is executed, and the program continues running 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 continued without crashing.")
This is especially useful in data analysis when dealing with messy, real-world data. You might have missing values or incorrect data types, and error handling helps your program manage these issues without stopping.
What is the data type of the value assigned to the variable launch_status in the following Python code?
launch_status = True
Which control structure is best suited for repeating a task a specific number of times, once for each item in a collection?
With these building blocks—variables, control structures, functions, and error handling—you have the foundation for writing powerful Python scripts for data analysis.