Python for Data Science Essentials
Python Basics
Storing Information
In programming, we need a way to store and label information. We do this with variables. Think of a variable as a labeled box where you can keep a piece of data. You give the box a name, and you can put something inside it. Later, you can refer to the box by its name to see what's inside or even change its contents.
variable
noun
A symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name.
Creating a variable in Python is simple. You just choose a name, use the equals sign (=), and provide the data you want to store.
greeting = "Hello, world!"
user_age = 25
pi_approx = 3.14
is_learning = True
The data we store comes in different forms, called data types. The examples above show the most common ones:
- Strings (
str): Textual data, enclosed in quotes."Hello, world!"is a string. - Integers (
int): Whole numbers, like25. - Floats (
float): Numbers with decimal points, like3.14. - Booleans (
bool): Represents one of two values:TrueorFalse. These are crucial for making decisions in your code.
Python is smart enough to figure out the data type on its own. If you're ever unsure, you can use the built-in type() function to check.
# Let's check the type of the user_age variable
print(type(user_age))
# The output will be:
# <class 'int'>
Controlling the Flow
A program doesn't just run from top to bottom. Often, you need it to make decisions or repeat actions. This is handled by control structures.
The most basic way to make a decision is with an if statement. It checks if a condition is true. If it is, a specific block of code runs. You can also provide alternative paths with elif (else if) and else.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("Better bring a jacket.")
else:
print("The weather is pleasant.")
What if you need to do something over and over? That's where loops come in.
A for loop is used to iterate over a sequence, like a list of items or a range of numbers. It's perfect when you know exactly how many times you want to repeat an action.
# This loop will run 5 times, for numbers 0 through 4
for number in range(5):
print(f"Repeating action number {number}")
A while loop, on the other hand, keeps running as long as a certain condition remains true. It's useful when you don't know the number of repetitions in advance.
countdown = 3
while countdown > 0:
print(f"{countdown}...")
countdown = countdown - 1 # Decrease the value
print("Liftoff!")
Use a
forloop when you have a definite number of iterations. Use awhileloop when you need to loop until a condition changes.
Packaging and Reusing Code
As your programs get more complex, you'll find yourself writing the same lines of code again and again. To stay organized and efficient, you can package chunks of code into functions.
A function is a named, reusable block of code that performs a specific task. You define it once and can then 'call' it whenever you need it.
# Define a function to greet a person
def greet(name):
message = f"Hello, {name}! Welcome."
return message
# Call the function with different arguments
print(greet("Alice"))
print(greet("Bob"))
Functions can take inputs, called arguments (like "Alice"), and can produce an output using a return statement.
Python also comes with a vast standard library of pre-written code organized into modules. A module is simply a file containing Python definitions and statements. To use code from a module, you import it.
# Import the 'math' module to use its functions
import math
# Now we can use the sqrt function from the math module
number = 81
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}")
Handling Errors
Sometimes, things go wrong. Your code might try to divide by zero or open a file that doesn't exist. When Python encounters a situation it can't handle, it raises an error, or an exception, and the program crashes.
Instead of letting the program crash, you can anticipate and handle these errors gracefully using a try...except block.
The logic is straightforward: Python will first attempt to run the code inside the try block. If an error occurs, it skips the rest of the try block and executes the code inside the except block. If no error occurs, the except block is ignored.
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: You can't divide by zero!")
print("The program continues to run.")
Notice how the program didn't crash. It printed our custom error message and the final line was still executed. This is essential for building robust programs that don't fail unexpectedly.
What is the primary purpose of a function in programming?
Consider the following code snippet:
x = 10
y = "10"
Do x and y represent the same data type?