Loading notes...
Loading notes...
BCA • Chapter 4
Chapter 4 covers the creation and utilization of functions in Python. It details parameters, return values, variable-length arguments (*args, **kwargs), anonymous lambda functions, recursion, and variable scope.
As your programs grow larger and more complex, keeping all your code in a single, massive script becomes unmanageable. Functions allow you to break your program into smaller, reusable, and logical chunks. A function is essentially a named block of code designed to perform a specific task. By using functions, you improve readability, prevent code duplication (the DRY principle: Don't Repeat Yourself), and make debugging much easier.
4.1 Defining and Calling Functions
In Python, a function is defined using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. The code block within every function must be indented. To execute the function, you simply call it by its name followed by parentheses.
# Defining a simple function
def greet_user():
"""This is a docstring. It explains what the function does."""
print("Hello! Welcome to the BCA Python Course.")
# Calling the function
greet_user()
# Calling it again reuses the code without rewriting it
greet_user()4.2 Function Arguments (Parameters)
Information can be passed into functions as arguments. Parameters are the variables specified inside the parentheses in the function definition, while arguments are the actual values passed to the function when it is called.
# Function with parameters and a default argument
def create_profile(name, age, course="BCA"):
print(f"Name: {name}, Age: {age}, Course: {course}")
# Positional arguments
create_profile("Basant", 21)
# Output: Name: Basant, Age: 21, Course: BCA (default used)
# Keyword arguments (order doesn't matter)
create_profile(age=22, name="Ravi", course="MCA")
# Output: Name: Ravi, Age: 22, Course: MCA4.3 Return Statements
Instead of printing a result directly to the console, a function can return a computed value back to the caller using the `return` statement. This allows the calling code to store the result in a variable or use it in further calculations. If a function does not have a `return` statement, it implicitly returns `None`.
def calculate_area(length, width):
area = length * width
return area # Sends the value back
# The returned value is caught and stored in 'room_area'
room_area = calculate_area(15, 10)
print(f"The area is {room_area} sq units.")
# Python can return multiple values as a Tuple
def get_user_stats():
return "Basant", 95, "A+"
# Unpacking the returned tuple
name, score, grade = get_user_stats()
print(f"{name} scored {score} ({grade})")4.4 Variable-Length Arguments (*args and **kwargs)
Sometimes you do not know in advance how many arguments will be passed into your function. Python allows you to handle this using `*args` (for non-keyword arguments) and `**kwargs` (for keyword arguments).
# *args collects extra positional arguments into a Tuple
def calculate_sum(*numbers):
total = 0
for num in numbers:
total += num
return total
print(calculate_sum(10, 20, 30)) # Output: 60
print(calculate_sum(5, 5)) # Output: 10
# **kwargs collects extra keyword arguments into a Dictionary
def print_student_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_student_info(name="Basant", city="Delhi", grade="A")4.5 Lambda Functions (Anonymous Functions)
A lambda function is a small, anonymous function defined without a name. It is created using the `lambda` keyword instead of `def`. Lambda functions can take any number of arguments but can only have ONE expression. They are often used as throw-away functions passed as arguments to higher-order functions like `map()` or `filter()`.
# Regular function
def square(x):
return x ** 2
# Equivalent Lambda function
# Syntax: lambda arguments : expression
square_lambda = lambda x: x ** 2
print(square_lambda(5)) # Output: 25
# Using lambda with built-in filter() to get only even numbers
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]4.6 Recursive Functions
Recursion is a programming technique where a function calls itself directly or indirectly to solve a smaller instance of the same problem. Every recursive function must have a Base Case (a condition that stops the recursion) to prevent infinite loops and stack overflow errors.
# Calculating factorial using recursion (n! = n * (n-1)!)
def factorial(n):
# Base case: prevents infinite recursion
if n == 0 or n == 1:
return 1
# Recursive step
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 (5 * 4 * 3 * 2 * 1)4.7 Variable Scope (Local vs Global)
Scope determines the visibility and lifetime of a variable. Variables defined inside a function are Local and cannot be accessed outside it. Variables defined outside any function are Global. If you need to modify a global variable from within a function, you must use the `global` keyword.
score = 0 # Global variable
def update_score():
global score # Tells Python to use the global 'score'
score += 10
local_var = "I am local"
update_score()
print(score) # Output: 10
# print(local_var) # This would crash with a NameError