6 - Functions & Modules
6 - Functions & Modules
Syntax:
def greet(name):
return f"Hello, {name}!"
Key Points:
• Defined using def keyword.
• Function name should be meaningful.
• Use return to send a value back.
Types of Arguments:
1. Positional Arguments
2. Default Arguments
def greet(name="Guest"):
return f"Hello, {name}!"
3. Keyword Arguments
student(age=20, name="Bob")
Syntax:
square = lambda x: x * x
print(square(4)) # Output: 16
Example:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
4. Recursion in Python
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
Important Notes:
• Must have a base case to avoid infinite recursion.
• Used in algorithms like Fibonacci, Tree Traversals.
Importing Modules
Python provides built-in and third-party modules.
import math
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
Example usage:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
In Python, variables have scope (where they can be accessed) and lifetime (how
long they exist). Variables are created when a function is called and destroyed
when it returns. Understanding scope helps avoid unintended errors and improves
code organization.
x = 10 # Global variable
def my_func():
x = 5 # Local variable
print(x) # Output: 5
my_func()
print(x) # Output: 10 (global x remains unchanged)
x = 10 # Global variable
def modify_global():
global x
x = 5 # Modifies the global x
modify_global()
print(x) # Output: 5
This allows functions to change global variables, but excessive use of global is
discouraged as it can make debugging harder.
Docstrings are used to document functions, classes, and modules. In Python, they
are written in triple quotes. They are accessible using the __doc__ attribute. Here’s
an example:
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
return a + b
Summary