**Python: Functions and Libraries

In this lesson, you'll delve into the world of Python functions and discover how they help you write more organized and reusable code. You will also get introduced to essential libraries like NumPy and Pandas, which are the backbone of data science in Python.

Learning Objectives

  • Define and use functions with arguments and return values.
  • Understand the concept of code reusability through functions.
  • Import and use NumPy for numerical computations.
  • Import and use Pandas for data manipulation and analysis.

Text-to-Speech

Listen to the lesson content

Lesson Content

Introduction to Functions

Functions are blocks of reusable code that perform a specific task. They make your code more organized, readable, and efficient. Instead of writing the same code multiple times, you can define it once within a function and call the function whenever needed.

Defining a Function:

def greet(name):
  print(f"Hello, {name}!")

greet("Alice")  # Calling the function
greet("Bob")

In this example, greet is the function name, name is the parameter (input), and print(f"Hello, {name}!") is the code inside the function (the function's body). The def keyword starts the function definition.

Functions with Return Values:
Functions can also return values using the return statement.

def add_numbers(x, y):
  sum = x + y
  return sum

result = add_numbers(5, 3)
print(result) # Output: 8

Introduction to NumPy

NumPy (Numerical Python) is a fundamental library for numerical computing in Python. It provides powerful tools for working with arrays, which are essential for data science.

Importing NumPy:

import numpy as np

It's common practice to import NumPy with the alias np.

Creating NumPy Arrays:

my_array = np.array([1, 2, 3, 4, 5])
print(my_array)  # Output: [1 2 3 4 5]

Basic NumPy Operations:

import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

# Element-wise addition
sum_array = array1 + array2
print(sum_array)  # Output: [5 7 9]

# Multiplication
product_array = array1 * 2
print(product_array) # Output: [2 4 6]

Introduction to Pandas

Pandas is a powerful library for data manipulation and analysis. It provides data structures like DataFrames, which are similar to spreadsheets or SQL tables.

Importing Pandas:

import pandas as pd

It's common practice to import pandas with the alias pd.

Creating a DataFrame:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 28],
        'City': ['New York', 'London', 'Paris']}

df = pd.DataFrame(data)
print(df)

DataFrame Basics:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 28],
        'City': ['New York', 'London', 'Paris']}

df = pd.DataFrame(data)

# Accessing a column
print(df['Name'])

# Accessing a row
print(df.loc[0])  # Access the row with index 0
Progress
0%