Python Unit III
Python Unit III
Python
UNIT- III: FUNCTIONS AND MODULAR PROGRAMMING
Suppose we need to create a program to make a circle and color it. We can create
two functions to solve this problem:
1. function to create a circle
2. function to color the shape
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
SYNTAX
CREATE A FUNCTION
A function is defined using the def keyword, followed by the function name,
parentheses (which may contain parameters), and a colon. The function's
body is indented.
The def keyword stands for define.
After creating a function in Python we can call it by using the name of the
functions followed by parenthesis containing parameters of that particular
function. Below is the example for calling def function Python.
def fun():
print("Welcome to GFG")
Output
Welcome to GFG
FUNCTIONS IN PYTHON – WITH & WITHOUT RETURN TYPE
# Example usage
check_prime(7)
check_prime(12)
Case: check_prime(7)
Check ≤ 1
→
7 <= 1 False skip.→
For loop
for i in range(2, 7):
→ Loop will check divisors 2, 3, 4, 5, 6.
i 7%i Result Action
No divisor found.
Loop ends without break.
FUNCTIONS IN PYTHON – WITH & WITHOUT RETURN TYPE
Parameter
A parameter is a variable used inside the function definition.
It acts like a placeholder that will receive a value when the function is
called.
Parameters exist only inside the function until it is executed.
Argument
An argument is the actual value that you pass to the function when calling
it.
This value gets assigned to the parameter inside the function.
Arguments are the real data used by the function.
student(fname='Geeks',
lname='Practice')
student(lname='Practice',
fname='Geeks')
3. Default Arguments
print(add_numbers(10, 20))
print(add_numbers(5, 10, 15, 20))
2. **kwargs → Arbitrary Keyword Arguments
**kwargs is used to pass a variable number of keyword
arguments.
Inside the function, kwargs is treated as a dictionary containing
key-value pairs.
This is useful when we want to provide named values without
knowing the exact number in advance.
student_info(name="Priya", age=20,
course="Python")
RECURSION IN PYTHON
Recursion is a programming technique where a function calls itself
directly or indirectly to solve a problem.
It is commonly used to solve problems that can be broken into smaller,
similar subproblems.
A recursive function must have:
→
[Link] Case Condition to stop recursion (prevents infinite loop).
→
[Link] Case Function calls itself with smaller/simpler input.
Advantages of Recursion
Makes code simple and elegant for problems like factorial, Fibonacci,
tree traversal, etc.
Naturally fits problems defined in terms of smaller subproblems.
Disadvantages
Uses more memory (each call is stored in the call stack).
Slower compared to iterative solutions for large inputs.
Factorial using Recursion Fibonacci using Recursion
print(factorial(5)) print(fibonacci(6))
120 8
Dry Run for factorial(5)
→
Call 1: factorial(5) 5 * factorial(4)
→
Call 2: factorial(4) 4 * factorial(3)
→
Call 3: factorial(3) 3 * factorial(2)
→
Call 4: factorial(2) 2 * factorial(1)
→ →
Call 5: factorial(1) base case returns
1
Now results bubble back up:
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
LAMBDA EXPRESSIONS IN PYTHON
Definition
A lambda expression is an anonymous function in Python (a function
without a name).
It can take any number of arguments but can contain only one
expression.
syntax
square = lambda x: x * x
print(square(5))
25
add = lambda a, b: a + b
print(add(10, 20))
30
SCOPE AND LIFETIME OF VARIABLES
If we will try to use this local variable outside the function then let’s see
what will happen.
SCOPE AND LIFETIME OF VARIABLES
Definition: The enclosing scope exists for nested functions. It is
the scope of the outer (enclosing) function.
Visibility: An inner function can access variables from its enclosing
scope. However, these variables are not visible from outside the
outer function.
Lifetime: Enclosing variables exist as long as the outer function is
running. They live on for as long as the nested function references
them.
def outer_function(): Hello from Outer Function!
message = "Hello from Outer Function!" # Enclosing
variable
def inner_function():
print(message) # Accessing enclosing variable
inner_function()
outer_function()
SCOPE AND LIFETIME OF VARIABLES
Modifying Enclosing Variable with nonlocal
Normally, you cannot directly change enclosing variables inside the inner
function.
But with nonlocal, you can modify them.
def outer_function():
count = 0
def inner_function():
nonlocal count # tells Python to use the enclosing variable
count += 1
print("Count inside inner:", count)
inner_function()
inner_function()
print("Final count in outer:", count) Count inside inner: 1
Count inside inner: 2
outer_function() Final count in outer: 2
SCOPE AND LIFETIME OF VARIABLES
Python Global variables
Global variables are the ones that are defined and declared outside any
function and are not specified to any function. They can be used by any
part of the program.
def f(): I love Python
print(s)
# Global scope
s = "I love Python"
f()
# Global scope
s = "I love AI"
f()
print(s)
myfunc()
print(x)
SCOPE AND LIFETIME OF VARIABLES
Built-in (B) scope
The built-in scope contains Python's standard functions and keywords
like print() and len().
Visibility: Built-in names are accessible everywhere and are
automatically loaded.
Lifetime: Built-in names are available as long as the interpreter runs.
Hello, World!
5
15
SCOPE AND LIFETIME OF VARIABLES
Built-in (B) scope
The built-in scope contains Python's standard functions and keywords
like print() and len().
Visibility: Built-in names are accessible everywhere and are
automatically loaded.
Lifetime: Built-in names are available as long as the interpreter runs.
Hello, World!
5
15
BUILT-IN FUNCTIONS
Built-in functions in Python are a set of pre-defined functions that are always
available for use without needing to import any modules. They provide essential
functionalities for common tasks, simplifying code and improving efficiency.
Key characteristics of Python built-in functions:
Pre-defined:
They are part of the core Python language and are automatically loaded when
the interpreter starts.
No import required:
You can directly call them in your code without using import statements.
Versatile:
They cover a wide range of operations, including data type manipulation,
mathematical calculations, input/output handling, and more.
Efficiency:
They are often implemented in optimized C code, making them highly efficient
for common operations.
BUILT-IN FUNCTIONS
Function Example Description
input() name = input("Enter your name: ") Gets user input from the console and assigns it to a variable
sum() sum([1, 2, 3, 4, 5]) Returns the sum of all elements in the list
fun(2)
Type Definition Example Output Explanation
def fun(*args):
Accepts unknown number Python
4. Variable Length for arg in args: *args collects multiple
of arguments using *args or Java
Argument Functions print(arg) arguments into a tuple.
**kwargs. C++
fun("Python","Java","C++")
def fun(num):
5. Functions with Return Functions can return return num * num The function returns the square
25
Value results using return. res = fun(5) of the number 5.
print(res)
# [Link]
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Explanation:
math module is imported using import math.
We access the constant pi using [Link] and then the value is printed
as part of a formatted string.
EXTERNAL MODULES
Instead of importing the entire module, we can import only the functions
or variables we need using the from keyword. This makes the code cleaner
and avoids unnecessary imports.
import math as m
result = [Link](25)
print("Square root of 25:", result)
2. random Module:
This module is used for generating pseudo-random numbers and making
random selections. Key functions include:
random(): Returns a random float between 0.0 (inclusive) and 1.0
(exclusive).
randint(a, b): Returns a random integer between a and b (inclusive).
choice(sequence): Returns a random element from a non-empty
sequence.
shuffle(list): Shuffles a list in place.
sample(population, k): Returns a list of k unique random elements
from a population.
RANDOM MODULE:
import random
print([Link](1, 10)) # Output: A random integer between 1 and 10
my_list = [1, 2, 3, 4, 5]
print([Link](my_list)) # Output: A random element from my_list
time Module:
This module provides various time-related functions, including handling time,
measuring elapsed time, and formatting dates. Important functions include:
time(): Returns the current time as a floating-point number representing
the number of seconds since the epoch.
sleep(seconds): Pauses the program execution for a specified number of
seconds.
ctime([seconds]): Converts a time expressed in seconds since the epoch to
a string representing local time.
strftime(format, t): Formats a time tuple or struct_time object according to
a format string.
TIME MODULE
import time
1757904576.9638648
Mon Sep 15 [Link] 2025
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)