Python for Data Analysis
Python Basics
Storing Information
Think of a variable as a labeled box where you can store information. You give the box a name (the variable name) and put something inside it (the value). This lets you save data and refer to it later by its name.
Python works with several basic types of data. The most common are:
- Integers: Whole numbers, like 10, -5, or 0.
- Floats: Numbers with a decimal point, like 3.14 or -0.001.
- Strings: Text, which you write inside quotes. For example,
"Hello, world!". - Booleans: Represent truth values. They can only be
TrueorFalse.
These are the fundamental building blocks for handling data. Let's see them in action.
# Assigning values to variables
student_count = 25 # An integer
average_score = 88.5 # A float
subject = "Data Analysis" # A string
is_passing = True # A boolean
# You can print the variables to see their values
print(student_count)
print(subject)
Making Decisions and Repeating Actions
Programs often need to make decisions or perform actions repeatedly. This is where control structures come in. They control the flow of your code.
The most basic decision-maker is the 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) to check other conditions, and else to run code if none of the conditions are met.
If the score is above 90, the grade is A. Else if it's above 80, the grade is B. Otherwise, the grade is C.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
print(grade) # This will print "B"
When you need to do something over and over, you use a loop. A for loop is great for iterating through a sequence, like a list of items. It performs an action for each item in the sequence.
# We have a list of expenses
expenses = [120, 45, 80, 210]
total = 0
# Loop through each expense and add it to the total
for expense in expenses:
total = total + expense
print("Total expenses:", total)
A while loop runs as long as a certain condition remains true. It's useful when you don't know exactly how many times you need to repeat something.
count = 5
# This loop will run as long as count is greater than 0
while count > 0:
print(count)
count = count - 1
print("Liftoff!")
Reusing Code
As you write more code, you'll find yourself repeating the same steps. Functions let you bundle up a piece of code, give it a name, and run it whenever you want. Think of it like a recipe: you write it once and can use it many times.
Defining a function is simple. You use the def keyword, followed by the function name and any inputs (called arguments) it needs.
# Define a function to calculate the area of a rectangle
def calculate_area(length, width):
area = length * width
return area
# Call the function with different arguments
area1 = calculate_area(10, 5)
area2 = calculate_area(7, 3)
print("Area 1 is:", area1)
print("Area 2 is:", area2)
Python also has a vast collection of pre-written code organized into modules. These are like toolkits filled with functions you can use. To access them, you just need to import the module.
For example, the math module contains many useful mathematical functions.
# Import the math module
import math
# Use the sqrt function from the math module
number = 64
square_root = math.sqrt(number)
print("The square root of 64 is", square_root)
Handling Errors
Errors, or exceptions, are a natural part of programming. Code doesn't always run perfectly. For instance, you might try to divide a number by zero or open a file that doesn't exist. Without a plan, these errors would crash your program.
Python provides a way to anticipate and manage these errors using a try...except block. 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 stopping.
numerator = 10
denominator = 0
try:
# This line will cause a ZeroDivisionError
result = numerator / denominator
print(result)
except ZeroDivisionError:
# This block runs because the error occurred
print("Oops! You can't divide by zero.")
print("The program continued without crashing.")
Error handling is crucial for writing robust programs that can gracefully handle unexpected situations. It’s like having a safety net for your code.
What is the data type of the value 17.5 in Python?
Which of the following describes a variable in programming?