Functions in Python - Beginner Friendly Notes
A function is a block of reusable code that performs a specific task.
Why Use Functions?
- Avoid repeating code
- Make your program organized
- Make code easier to debug
- Increase reusability
How to Define a Function?
def function_name():
# code
Example 1: Simple Function
def greet():
print("Hello, welcome to Python!")
Example 2: Function with Parameters
def add(a, b):
print(a + b)
Example 3: Return Value
def multiply(x, y):
return x * y
Example 4: Default Parameters
def greet(name="User"):
print("Hello", name)
Example 5: *args
def total(*numbers):
print(sum(numbers))
Example 6: **kwargs
def details(**info):
print(info)
Example 7: Nested Function
def outer():
def inner():
print("Inner")
inner()
Example 8: Lambda Function
square = lambda x: x * x
Example 9: Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
Summary:
- Simple function
- Parameters
- Return values
- Default values
- *args
- **kwargs
- Lambda
- Recursion