Python for Data Science
Python Basics
Storing Information
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 in the box whenever you want.
The information you store has a type. The most common types are:
- Integers: Whole numbers, like 10, -5, or 0.
- Floats: Numbers with a decimal point, like 3.14 or -0.5.
- Strings: Text, wrapped in single or double quotes, like 'hello' or "data science".
- Booleans: Can only be
TrueorFalse. They're perfect for asking yes-or-no questions.
# An integer
project_year = 2024
# A float
pi_approx = 3.14
# A string
user_name = "Alex"
# A boolean
is_active = True
print(project_year)
print(user_name)
Sometimes you need to store a collection of items, like a list of temperatures or names. For that, you can use a list, which is just a sequence of items inside square brackets.
# A list of strings
team_members = ["Alex", "Beth", "Charlie"]
# A list of numbers
daily_temps = [68.5, 71.0, 65.2, 73.8]
print(team_members[0]) # Prints 'Alex'
Making Decisions and Repeating Actions
Programs often need to make decisions. Just like you might decide to take an umbrella if it's raining, your code can perform different actions based on certain conditions. This is done with if, elif (else if), and else statements.
temperature = 75
if temperature > 80:
print("It's hot outside.")
elif temperature < 60:
print("It's chilly, bring a jacket.")
else:
print("The weather is pleasant.")
What if you need to do the same thing over and over? Instead of writing the same code multiple times, you use a loop. A for loop is great for going through each item in a list.
numbers = [1, 2, 3, 4, 5]
for number in numbers:
# This code runs for each item in the list
print(number * 2)
Another type of loop is the while loop, which keeps running as long as a certain condition is true. It's useful when you don't know exactly how many times you'll need to repeat the action.
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1 # Decrease the value
print("Blast off!")
Organizing Your Code
As your programs get more complex, you'll want to keep them organized and avoid repeating yourself. Functions are the solution. A function is a named, reusable block of code that performs a specific task, like a recipe you can use again and again.
# Define a function to add two numbers
def add_numbers(x, y):
return x + y
# Call the function and store the result
sum_result = add_numbers(5, 3)
print(sum_result) # Prints 8
Python also has a vast collection of pre-written code in files called modules. Think of a module as a cookbook full of recipes (functions) you can use. To access them, you just need to import the module.
# Import the math module to access its functions
import math
# Use the sqrt function from the math module
result = math.sqrt(25)
print(result) # Prints 5.0
Handling Mistakes
Errors, called exceptions, are a normal part of programming. A program might crash if it tries to do something impossible, like divide a number by zero or open a file that doesn't exist. To prevent this, you can anticipate potential errors and handle them gracefully.
Python's try and except blocks let you test a block of code for errors. The try block contains the code that might cause a problem. If an error occurs, the code in the except block is run, and the program continues instead of crashing.
numerator = 10
denominator = 0
try:
# This line will cause a ZeroDivisionError
result = numerator / denominator
print(result)
except ZeroDivisionError:
# This code runs instead of the program crashing
print("Error: Cannot divide by zero.")
Now, let's test your understanding of these core concepts.
What is the data type of the variable x in the following Python code? ```python
x = -15
What is the primary purpose of a for loop in Python?
With these fundamentals, you have the building blocks to start writing Python scripts and dive into the powerful libraries used in data science.