Python_Functions_Guide
Python_Functions_Guide
In Python, a function is a block of reusable code that is used to perform a specific action.
Functions help make programs modular, readable, and easier to manage.
Python provides both built-in functions (like print(), len(), etc.) and user-defined functions.
Function Syntax
def function_name(parameters):
"""docstring"""
statement(s)
return value
Types of Functions
1. 1. Built-in Functions (e.g., print(), len(), type(), etc.)
2. 2. User-defined Functions
3. 3. Lambda Functions (Anonymous functions)
4. 4. Recursive Functions
- Required arguments
- Default arguments
- Keyword arguments
- Variable-length arguments (*args, **kwargs)
def greet(name):
"""This function greets to the person passed in as a parameter."""
print("Hello, " + name + "!")
greet("Alice")
Return Statement
Functions can return a value using the return statement. Example:
result = add(3, 4)
print(result) # Output: 7
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda keyword.
Example:
square = lambda x: x * x
print(square(5)) # Output: 25
Recursive Function
Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)