Python Functions - Study Notes
1. Functions
A function is a block of reusable code that performs a specific task.
2. Why Use Functions?
- Reusability: Write once, use many times.
- Modularity: Break large programs into small parts.
- Readability: Easier to understand and maintain code.
- Avoid repetition: No need to rewrite the same code again.
3. Types of Functions
- Built-in Functions: Already provided by Python (e.g., print(), len(), type()).
- User-defined Functions: Functions you create using def keyword.
- Lambda Functions: Anonymous, single-expression functions using lambda.
4. Adding a New Function
You define a new function using the def keyword:
def greet():
print("Hello, welcome!")
5. Function Syntax
def function_name(parameters):
# function body
return value # optional
Example:
def add(a, b):
return a + b
6. Definition and Uses
Definition: A named block of code that only runs when called.
Uses:
- Avoid redundancy
- Improve structure
- Handle complex tasks by splitting into simpler pieces
7. Flow of Execution
1. Function is defined using def.
2. It does not execute until it is called.
3. When called, control moves to the function.
4. After execution, control returns to the calling point.
8. Parameters and Arguments
- Parameter: Variable in the function definition.
- Argument: Actual value passed to the function.
def greet(name): # 'name' is a parameter
print("Hello", name)
greet("Aro") # "Aro" is an argument
9. Default Arguments
If no argument is passed, the default is used.
def greet(name="Guest"):
print("Hello", name)
greet() # Output: Hello Guest
greet("Aro") # Output: Hello Aro
10. Functions in Module
Modules contain Python code (functions, variables, etc.) in separate files.
Example: math module
import math
print([Link](16)) # Output: 4.0
You can also create your own module by saving functions in a .py file and importing them.