Functions and Modules
Section 2: Functions and Modules
Lesson 1: Defining Functions
1.1 Creating Functions with Parameters and Return Values
Functions in Python allow you to encapsulate code for reuse. They can have parameters and return values.
Example:
# Function with parameters and return value
def greet(name):
return "Hello, " + name + "!"
# Calling the function
result = greet("Alice")
print(result)
1.2 Scope of Variables
The scope of a variable defines where it can be accessed. Local variables are confined to the function they are defined in, while global variables are accessible throughout the entire script.
Example:
# Global variable
global_variable = "I am global"
# Function with local variable
def local_function():
local_variable = "I am local"
print(global_variable) # Accessing global variable
print(local_variable) # Accessing local variable
# Calling the function
local_function()
print(global_variable) # Global variable is accessible here
Lesson 2: Working with Modules
2.1 Introduction to Python Modules
Modules in Python are files containing Python code. They allow you to organize code into reusable units.
Example:
# Example module saved as mymodule.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
2.2 Importing and Using Modules
You can import modules in Python to use their functions and variables.
Example:
# Importing the module
import mymodule
# Using functions from the module
result_add = mymodule.add(5, 3)
result_multiply = mymodule.multiply(2, 4)
print("Addition Result:", result_add)
print("Multiplication Result:", result_multiply)
Alternatively, you can import specific functions or variables from a module.
Example:
# Importing specific functions
from mymodule import add, multiply
# Using the imported functions
result_add = add(5, 3)
result_multiply = multiply(2, 4)
print("Addition Result:", result_add)
print("Multiplication Result:", result_multiply)
In Section 2, we explored functions and modules in Python. Functions provide a way to encapsulate and reuse code, supporting parameters and return values. Understanding variable scope is crucial for managing data within and outside functions.
Modules, as reusable units of code, promote code organization and maintainability. Importing modules allows us to leverage their functions and variables in our scripts. As you incorporate functions and modules into your Python programming, you'll enhance code modularity, readability, and reusability. These concepts are foundational for building scalable and well-organized Python projects.