Python for Data Analysis
Python Basics
The Basic Rules of Python
Think of Python's syntax as its grammar. It’s a set of rules that define how a program is written and interpreted. Luckily, Python's grammar is known for being clean and readable. The most important rule to remember is that Python uses indentation, like spaces or tabs, to define blocks of code. Where other languages might use brackets or keywords, Python uses whitespace. This makes the code visually organized and easy to follow.
Let's start with the most basic building block: a variable. A variable is just a name you give to a value so you can use it later. You create one using an equals sign =.
greeting = "Hello, world!"
count = 5
# You can print the values to see them
print(greeting)
print(count)
In the example above, greeting and count are variables. The text starting with a # is a comment. Python ignores comments, but they're incredibly useful for leaving notes for yourself or others reading your code.
Types of Data
Variables can hold different kinds of data. These are called data types. Python has several built-in types, but let's focus on the most common ones you'll encounter in data analysis.
Integer
noun
A whole number, without a fractional part.
Integers (int) are for whole numbers, and floating-point numbers (float) are for numbers with decimals. Strings (str) are used for text and are enclosed in single or double quotes. Finally, Booleans (bool) represent one of two values: True or False.
# An integer
year = 2024
# A float
price = 19.99
# A string
name = "Alice"
# A boolean
is_active = True
You'll also work with collections of data. The most basic collection is a list, which is an ordered sequence of items. You create a list using square brackets [].
# A list of numbers
scores = [88, 92, 77, 95, 84]
# A list of strings
colors = ["red", "green", "blue"]
Controlling the Flow
Your code won't always run straight from top to bottom. Control structures let you execute certain blocks of code only if a condition is met, or repeat a block of code multiple times. This is what makes programs dynamic and intelligent.
The if statement runs a block of code only if a condition is True. You can add an else to run code if the condition is False. Use elif (short for "else if") to check multiple conditions.
age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior.")
To repeat code, you use loops. A for loop iterates over a sequence, like a list. A while loop continues as long as a condition is True.
# A for loop
colors = ["red", "green", "blue"]
for color in colors:
print(color)
# A while loop
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Liftoff!")
Packaging Code with Functions
As your programs get more complex, you'll find yourself writing the same bit of code over and over. Functions let you package a block of code, give it a name, and reuse it whenever you need it. This keeps your code organized and easy to maintain.
You define a function using the def keyword. A function can take inputs, called parameters, and can send a value back, called a return value.
# Define a function that takes one parameter
def greet(name):
message = "Hello, " + name + "!"
return message
# Call the function and store its return value
greeting = greet("Data Scientist")
print(greeting)
Functions are a cornerstone of good programming. They help you write DRY code, which stands for "Don't Repeat Yourself".
Handling Errors Gracefully
Sometimes, things go wrong. Your program might get unexpected input, or a file it needs might be missing. When Python encounters a situation it can't handle, it raises an error, or an exception, which typically crashes the program.
Instead of letting your program crash, you can anticipate potential errors 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:
number = int(user_input)
print("Your number is:", number)
except ValueError:
print("That's not a valid number!")
In this example, trying to convert "abc" into an integer causes a ValueError. Because we've caught this specific error, our program prints a helpful message instead of crashing. This is crucial for building robust programs that can handle real-world, messy data.
Now, let's test your understanding of these core concepts.
What is the primary purpose of indentation in Python?
What will be printed to the console after running this code snippet?
score = 75
result = ""
if score > 80:
result = "Pass"
else:
result = "Fail"
print(result)
With these fundamentals—syntax, data types, control structures, functions, and error handling—you have the foundation needed to start writing powerful Python scripts for data analysis.