**Python Functions & Introduction to NumPy

In this lesson, you'll learn about Python functions and how they make your code reusable and organized. We'll then dive into NumPy, a powerful library for numerical computation and data manipulation, which is essential for working with data in deep learning.

Learning Objectives

  • Define and use Python functions with and without parameters.
  • Understand the concept of function scope and variable visibility.
  • Learn the basics of the NumPy library and its array data structure.
  • Perform basic NumPy operations like array creation, indexing, and slicing.

Text-to-Speech

Listen to the lesson content

Lesson Content

Introduction to Python Functions

Functions are blocks of reusable code that perform a specific task. They help you organize your code, make it more readable, and reduce repetition. You define a function using the def keyword, followed by the function name, parentheses (), and a colon :. The code block within the function is indented.

# A simple function
def greet():
    print("Hello, world!")

greet() # Calling the function

Functions can also accept parameters (inputs) to perform more general tasks. These are specified inside the parentheses.

# Function with a parameter
def greet_name(name):
    print(f"Hello, {name}!")

greet_name("Alice") # Calling the function with an argument
greet_name("Bob")

Function Parameters and Return Values

Functions can accept multiple parameters. They can also return a value, which is sent back to the part of the code that called the function. If a function doesn't have a return statement, it implicitly returns None.

# Function with two parameters and a return value
def add(x, y):
    result = x + y
    return result

sum_result = add(5, 3)
print(sum_result) # Output: 8

Functions can also have default parameter values. This means that if a value for the parameter is not provided when the function is called, the default value will be used.

def greet_with_default(name="Guest"):
    print(f"Hello, {name}!")

greet_with_default()  # Output: Hello, Guest!
greet_with_default("Charlie") # Output: Hello, Charlie!

Introduction to NumPy

NumPy (Numerical Python) is the fundamental package for scientific computing in Python. It provides powerful data structures, particularly the ndarray (n-dimensional array), which is much more efficient for numerical operations than Python lists.

To use NumPy, you must first import it:

import numpy as np

Arrays are created in several ways:

# Creating an array from a list
my_array = np.array([1, 2, 3, 4, 5])
print(my_array) # Output: [1 2 3 4 5]

# Creating an array of zeros
zeros_array = np.zeros(5) # Creates an array of 5 zeros.
print(zeros_array) # Output: [0. 0. 0. 0. 0.]

# Creating an array of ones
ones_array = np.ones((2, 3)) # Creates a 2x3 array of ones
print(ones_array)

# Creating an array with a range of values
range_array = np.arange(0, 10, 2) # Start at 0, end before 10, step of 2
print(range_array) # Output: [0 2 4 6 8]

NumPy Array Indexing and Slicing

You can access elements in a NumPy array using indexing and slicing, similar to Python lists, but with enhanced capabilities for multi-dimensional arrays. Indexing starts at 0.

my_array = np.array([10, 20, 30, 40, 50])
print(my_array[0])     # Access the first element: 10
print(my_array[2:4])   # Slice from index 2 up to (but not including) index 4: [30 40]

# Example with a 2D array:
my_2d_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(my_2d_array[0, 1])  # Access element in row 0, column 1: 2
print(my_2d_array[1:]) # Slice from row 1 to the end

NumPy also supports boolean indexing and other advanced indexing methods. Boolean indexing is very useful for filtering data based on conditions.

NumPy Array Operations

NumPy allows you to perform mathematical operations on entire arrays at once, which is much more efficient than using loops with Python lists.

# Element-wise addition
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum_array = a + b
print(sum_array) # Output: [5 7 9]

# Multiplication by a scalar
scaled_array = a * 2
print(scaled_array) # Output: [2 4 6]

# Other operations:
print(np.mean(a))     # Calculates the mean
print(np.std(a))      # Calculates the standard deviation
Progress
0%