Python Functions - Class Notes
Definition:
A function is a reusable block of code that performs a specific task. Functions help reduce repetition,
make code more organized, and improve readability.
Syntax:
def function_name(parameters):
# code block
return value (optional)
Example:
def greet(name):
print("Hello", name)
greet("Alice") # Output: Hello Alice
Advantages of Using Functions:
- Code reusability
- Easier to debug and manage
- Reduces code length
Types of Functions:
1. Built-in Functions: Functions like print(), len(), int(), etc.
2. User-defined Functions: Functions created by users using 'def' keyword.
Parameters and Arguments:
- Parameters: Placeholders in function definitions.
- Arguments: Actual values passed to functions.
- Types: Positional, Keyword, Default, Variable-length (*args, **kwargs)
Return Statement:
Functions may return a value using 'return' keyword.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
Variable-length Arguments:
*args - for variable number of positional arguments
**kwargs - for variable number of keyword arguments
Example:
def show(*args):
for arg in args:
print(arg)
Recursion:
A function that calls itself is known as a recursive function.
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120