Lesson 2.3: Functions and Modules in Python
Functions and modules make Python code reusable, organized, and easy to manage.
1. Functions in Python
A function is a block of code that runs only when called.
Defining a Function:
Calling a Function:
Function with Parameters:
Default Parameters:
Keyword Arguments:
Variable Number of Arguments:
2. Scope of Variables
-
Local variable → defined inside a function, used only there.
-
Global variable → defined outside a function, can be used everywhere.
3. Modules in Python
A module is a file containing Python code (functions, classes, variables).
Using Built-in Modules:
Import Specific Functions:
Renaming Module (alias):
Creating Your Own Module:
Create a file mymath.py
Use it in another file:
✅ In Summary:
-
Functions help reuse code with
defkeyword. -
Parameters can be default, keyword, or variable-length.
-
Modules are files with reusable code; you can use built-in or custom ones.
