Functions and Modules
In any program, some parts of code may need to be reused. Python offers functions and modules to help us organize and reuse code in a clean and manageable way.
What is a Function?
A function is a block of code that performs a specific task. It runs only when it is called.
Why use functions?
- To avoid repeating code
- To organize your program better
- To make your code more readable and reusable
Function with Parameters
Functions can accept parameters (inputs) and return values.
Default and Keyword Arguments
You can give a default value to a parameter.
You can also use keyword arguments:
Return Statement
Functions can return a value using return
.
What is a Module?
A module is simply a Python file that contains functions, variables, or classes. You can use a module in another file using the import
keyword.
Using Built-in Modules
Example: Using the math
module
Creating Your Own Module
Suppose you have a file named mymodule.py
:
Then in another file:
Usingfrom
Keyword
You can import specific functions:
Summary
- Use functions to reuse and organize your code.
- Functions can take parameters and return values.
- A module is a file that contains Python code.
- Use
import
to use code from other modules. - Python has many built-in modules (like
math
,random
, etc.)