0% found this document useful (0 votes)
8 views6 pages

Module 5 Functions

Module-5 Functions provides a comprehensive guide to Python functions, including pre-defined and user-defined functions, parameters, return statements, and recursion. It covers examples of using built-in functions, defining functions with parameters, and the internal workflow of recursion. Additionally, it explains the use of modules and demonstrates practical applications of these concepts.

Uploaded by

klraju00007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

Module 5 Functions

Module-5 Functions provides a comprehensive guide to Python functions, including pre-defined and user-defined functions, parameters, return statements, and recursion. It covers examples of using built-in functions, defining functions with parameters, and the internal workflow of recursion. Additionally, it explains the use of modules and demonstrates practical applications of these concepts.

Uploaded by

klraju00007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module-5 Functions

December 1, 2025

1 Python Functions – Complete Guide


Covers: Pre-defined functions, User-defined functions, Parameters, Return, Branching, Looping,
Data Structures in Functions, Recursion, Internal Workflow of Recursion, Modules.

1.1 1. Pre-defined Functions


Examples of using Python built-in (pre-defined) functions.

[1]: # � Easy: Using simple built-in functions


print("Length of list:", len([1,2,3])) # len() returns number of items
print("Max value:", max(4,9,2)) # max() returns maximum among␣
↪arguments

# � Medium: Type conversion and parsing


s = "123" # string containing digits
num = int(s) # int() converts numeric string␣
↪to integer

print("Converted number:", num)

# � Medium-difficulty: Built-ins with data structures


nums = [10, 20, 30, 40] # sample list
print("Sum of list:", sum(nums)) # sum() aggregates numeric␣
↪iterables

print("Sorted list:", sorted(nums)) # sorted() returns a new sorted␣


↪list

Length of list: 3
Max value: 9
Converted number: 123
Sum of list: 100
Sorted list: [10, 20, 30, 40]

1.2 2. User-defined Functions


How to define and call functions using def, examples with parameters and return.

[2]: # � Easy: Basic function


def _abc(x,y):

1
z = x + y
if z>10:
return z
else:
return 0

a = 10
b = 20
print("Value : ",_abc(a,b))
print("Value : ",_abc(-20,10))

def greet(): # define a function with no␣


↪parameters

return "Hello!" # return a string

print(greet()) # call the function and print␣


↪return value

# � Medium: Function with parameters


def add(a, b): # 'a' and 'b' are formal␣
↪parameters

return a + b # return sum

print("Addition:", add(5, 7)) # call with actual parameters 5␣


↪and 7

# � Medium-difficulty: Function operating on list


def square_list(lst): # accepts a list and returns␣
↪processed list

return [x*x for x in lst] # list comprehension squares␣


↪each element

print("Squared list:", square_list([1,2,3,4]))

Value : 30
Value : 0
Hello!
Addition: 12
Squared list: [1, 4, 9, 16]

1.3 3. Formal and Actual Parameters


Distinguish formal parameters (in definition) from actual parameters (in call).

2
[3]: # Formal parameters: defined in function
# Actual parameters: values passed during call

def multiply(x, y): # x,y are formal parameters


return x * y

result = multiply(6, 7) # 6,7 are actual parameters


print("Multiplication:", result)

# Default parameters
def power(base, a,exp=2,b=1): # exp has default value 2
return base ** exp

print("Power default exp:", power(5,2,1)) # uses default exp=2


print("Power exp=3:", power(5,3,1)) # override default

Multiplication: 42
Power default exp: 5
Power exp=3: 5

1.4 4. Return Statement


Returning values from functions, including multiple return values.

[4]: # Simple return


def get_message():
return "Returned value"

print(get_message())

# Returning multiple values (as a tuple)


def stats(a,b):
return a+b, a*b

s,p = stats(3,4) # tuple unpacking of returned␣


↪values

print("Sum:", s)

Returned value
Sum: 7

1.5 5. Using Branching, Looping and Data Structures in Functions


Examples showing if/elif/else, loops, and using lists within functions.

[5]: # Function using branching (if/elif/else)


def grade(score):
if score >= 90:
return "A"

3
elif score >= 75:
return "B"
else:
return "C"

print("Grade:", grade(82))

# Function using loop to compute factorial


def factorial(n):
f = 1
for i in range(1, n+1):
f *= i
return f

print("Factorial:", factorial(5))

# Function using data structures (list processing)


def count_even(lst):
count = 0
for x in lst:
if x % 2 == 0:
count += 1
return count

print("Even count:", count_even([1,2,3,4,5,6]))

Grade: B
Factorial: 120
Even count: 3

1.6 6. Recursion
Recursive functions, base case and recursive case examples.

[8]: # Simple recursive factorial


def rec_factorial(n):
if n == 0:
return 1
return n * rec_factorial(n-1)
a = '''
for n=5, 5 * 24
for n=4, 4 * 6
for n=3, 3 * 2
for n=2, 2 * 1
for n=1, 1 * 1
'''
print("Recursive factorial:", rec_factorial(5))

4
# Recursive sum of list
def rec_sum(lst):
if not lst: # base case: empty list
return 0
return lst[0] + rec_sum(lst[1:])

print("Recursive sum:", rec_sum([1,2,3,4,5]))

a ='''
result = rec_sum([1,2,3,4,5]) ##15

for [1,2,3,4,5], return 1 + 14


for [2,3,4,5], return 2 + 12
for [3,4,5], return 3 + 9
for [4,5], return 4 + 5
for [5], return 5 + 0
for [], return 0
'''

Recursive factorial: 120


Recursive sum: 15

1.7 7. Internal Workflow of Recursion


Trace recursion calls to understand call stack, entry and exit of each call.

[9]: # Trace recursion using print statements to show call flow


def trace_factorial(n):
print(f"Entering: {n}")
if n == 0:
print("Returning 1")
return 1
result = n * trace_factorial(n-1)
print(f"Returning: {result} (from n={n})")
return result

print(trace_factorial(4))

Entering: 4
Entering: 3
Entering: 2
Entering: 1
Entering: 0
Returning 1
Returning: 1 (from n=1)
Returning: 2 (from n=2)
Returning: 6 (from n=3)
Returning: 24 (from n=4)
24

5
1.8 8. Modules
Using and importing modules, from-import, and standard library examples.

[10]: # Using standard math module


import math

print("Square root of 16:", [Link](16)) # use module function


print("Pi constant:", [Link]) # access constant

# Importing specific function


from math import factorial as math_fact # import specific function with␣
↪alias

print("Factorial using math module:", math_fact(6))

Square root of 16: 4.0


Pi constant: 3.141592653589793
Factorial using math module: 720

You might also like