Working with Functions in Python
1. Introduction to Functions
A function is a block of reusable code that performs a specific task. Functions help in
modularity, code reusability, and better organization.
2. Types of Functions
1. Built-in Functions – Provided by Python (e.g., print(), len(), max(), sum(), etc.).
2. User-defined Functions – Created by users to perform specific tasks.
3. Defining a Function
Use the def keyword to define a function:
Example:
def greet():
print("Hello, Welcome to Python!")
4. Calling a Function
To execute a function, use its name followed by parentheses.
Example:
greet() # Output: Hello, Welcome to Python!
5. Function Parameters and Arguments
Parameters: Variables listed in the function definition.
Arguments: Values passed to the function.
Example:
def add(a, b): # 'a' and 'b' are parameters
return a + b
result = add(5, 3) # Passing arguments 5 and 3
print(result) # Output: 8
Types of Arguments:
1. Positional Arguments – Passed in the correct order.
2. Default Arguments – Assign a default value if no argument is provided.
3. Keyword Arguments – Passed with parameter names.
4. Variable-length Arguments – *args (Non-keyword arguments), **kwargs (Keyword
arguments).
Example:
def greet(name="Guest"):
print("Hello,", name)
greet("Alice") # Output: Hello, Alice
greet() # Output: Hello, Guest
6. Return Statement
A function can return a value using return.
Example:
def square(n):
return n * n
print(square(4)) # Output: 16
7. Scope of Variables
Local Variable – Defined inside a function, accessible only within it.
Global Variable – Defined outside any function, accessible throughout the program.
Example:
x = 10 # Global variable
def show():
y = 5 # Local variable
print(x + y)
show() # Output: 15
8. Lambda (Anonymous) Functions
A short, single-line function using lambda.
Example:
square = lambda x: x * x
print(square(5)) # Output: 25
9. Recursive Functions
A function calling itself.
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120