0% found this document useful (0 votes)
17 views49 pages

Python Unit III

Python

Uploaded by

shubashunmugam
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)
17 views49 pages

Python Unit III

Python

Uploaded by

shubashunmugam
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

UNIT III

Python
UNIT- III: FUNCTIONS AND MODULAR PROGRAMMING

Defining and calling functions. Function arguments: positional,


keyword, default, variable-length return statement. Recursion
and lambda expressions. Scope and lifetime of variables. Built-in
functions vs. user-defined functions. Importing and creating
modules. Python standard libraries (math, random, time)
DEFINING AND CALLING FUNCTIONS

Python Functions are a block of statements that does a specific task.

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.

def: Starts the function definition.


function_name: Name of the function.
parameters: Inputs passed to the function (inside ()), optional.
Indented code: The function body that runs when called.
CALLING A FUNCTION

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")

fun() # Driver code to call a function

Output
Welcome to GFG
FUNCTIONS IN PYTHON – WITH & WITHOUT RETURN TYPE

Functions in Python can be classified into two categories


based on their return behavior:
[Link] without return type
[Link] with return type

1. Functions without Return Type


👉
These functions do not return any value to the program that called them.
They are mainly used to perform an action, such as printing output,
displaying a message, or modifying data inside the function.
Even though no value is returned, Python internally returns None by
default.
These functions are useful when we only need the task to be done, and no
result needs to be sent back
def check_prime(num):
if num <= 1:
print(f"{num} is not a prime number")
else:
for i in range(2, num):
if num % i == 0:
7 is a prime number
print(f"{num} is not a prime number")
12 is not a prime number
break
else:
print(f"{num} is a prime number")

# 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

2 7%2=1 Not divisible continue

3 7%3=1 Not divisible continue

4 7%4=3 Not divisible continue

5 7%5=2 Not divisible continue

6 7%6=1 Not divisible continue

No divisor found.
Loop ends without break.
FUNCTIONS IN PYTHON – WITH & WITHOUT RETURN TYPE

2. Functions with Return Type


👉
These functions use the return statement to send a value back to the
caller.
The returned value can be stored in a variable, used in expressions, or
passed to other functions.
Functions with return type make programs more flexible because the
returned result can be reused.
Often used in calculations, string operations, and data processing.
Example: Finding the BMI (Body Mass Index) of a person

Person 1 BMI: 22.04


def calculate_bmi(weight, height):
Person 2 BMI: 26.12
bmi = weight / (height ** 2)
return bmi

# Calling the function


person1 = calculate_bmi(60, 1.65) # weight in kg, height in meters
person2 = calculate_bmi(80, 1.75)

print("Person 1 BMI:", round(person1, 2))


print("Person 2 BMI:", round(person2, 2))
PARAMETER VS ARGUMENT

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.

def greet(name): # here 'name' is a


parameter
print("Hello", name)
PARAMETER VS ARGUMENT

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.

greet("Suba") # here "Suba" is an


argument
greet("Anu") # here "Anu" is an argument
def square(num): # 'num' → parameter
return num * num

print(square(4)) # '4' → argument


print(square(7)) # '7' → argument
16
49
TYPES OF FUNCTION ARGUMENTS
Python supports various types of arguments that can be passed at the
time of the function call. In Python
1. Positional Arguments
In positional arguments, values are assigned to parameters based
on their order in the function call.
def nameAge(name, age): Case-1:
print("Hi, I am", name) Hi, I am Suraj
print("My age is ", age) My age is 27
print("Case-1:")
nameAge("Suraj", 27) Case-2:
print("\nCase-2:") Hi, I am 27
nameAge(27, "Suraj") My age is Suraj
2. Keyword Arguments

In keyword arguments, values are passed by explicitly specifying


the parameter names, so the order doesn’t matter.

def student(fname, lname): Geeks Practice


print(fname, lname) Geeks Practice

student(fname='Geeks',
lname='Practice')
student(lname='Practice',
fname='Geeks')
3. Default Arguments

A default argument is a parameter that assumes a default value if a


value is not provided in the function call for that argument. The
following example illustrates Default arguments to write functions
in Python.

def greet(name="Guest"): Hello Guest


print("Hello", name) Hello Suba

greet() # Uses default → Guest


greet("Suba")
4. Variable-length Arguments

In Python, sometimes we may not know in advance how many


values will be passed into a function. To handle this situation,
Python provides arbitrary arguments, also called variable-length
arguments.
This feature allows a function to accept any number of arguments
without explicitly defining them beforehand. It increases the
flexibility and reusability of functions.
There are two special symbols:
*args in Python (Non-Keyword Arguments)
**kwargs in Python (Keyword Arguments)
1. *args → Arbitrary Positional Arguments
*args is used to pass a variable number of positional arguments.
Inside the function, args is treated as a tuple, which means the
values can be accessed using indexing or loops.
This is useful when we want a function to work with an unknown
number of inputs.
def add_numbers(*args): 30
total = 0 50
for num in args:
total += num
return total

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.

def student_info(**kwargs): name: Priya


for key, value in [Link](): age: 20
print(f"{key}: {value}") course: Python

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

def factorial(n): def fibonacci(n):


if n == 0 or n == 1: # base case if n <= 1: # base case
return 1 return n
else: else:
return n * factorial(n - 1) # recursive case return fibonacci(n-1) + fibonacci(n-2)

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

No def keyword is used.


Used for short, simple
functions.
LAMBDA EXPRESSIONS IN PYTHON
When to Use Lambda?
When we need a short-term function without formally defining it
using def.
Often used with built-in functions like map(), filter(), and reduce().

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

Python Scope variable

In Python, a variable's scope determines its visibility and accessibility,


while its lifetime is the period it remains in memory. The hierarchy of
variable scopes is governed by the LEGB rule, which stands for Local,
Enclosing, Global, and Built-in.
SCOPE AND LIFETIME OF VARIABLES
SCOPE AND LIFETIME OF VARIABLES
Python Local variable
Local variables are those that are initialized within a function and are
unique to that function. It cannot be accessed outside of the function.
Let's look at how to make a local variable.
def f(): Python def f(): NameError: name 's' is not
defined
# local variable # local variable
s = "Python" s = "I love Geeksforgeeks"
print(s) print("Inside Function:", s)
f()
f() print(s)

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 and Local Variables with the Same Name


Now suppose a variable with the same name is defined inside the scope
of the function as well then it will print the value given inside the
function only and not the global value.
SCOPE AND LIFETIME OF VARIABLES

def f(): Me too.


s = "Me too." I love AI
print(s)

# Global scope
s = "I love AI"
f()
print(s)

Global and Local Variables with the Same Name


Now suppose a variable with the same name is defined inside the scope
of the function as well then it will print the value given inside the
function only and not the global value.
SCOPE AND LIFETIME OF VARIABLES
If you need to create a global variable, but are stuck in the local scope,
you can use the global keyword.
The global keyword makes the variable global.

def myfunc(): 300


global x
x = 300

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.

print("Hello, World!") # built-in print()


numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # built-in len()
print(sum(numbers))

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.

print("Hello, World!") # built-in print()


numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # built-in len()
print(sum(numbers))

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

print() print("Hello, World!") Prints output to the console

len() len("Python") Returns the length of a string

range() range(0, 10) Generates a range of integers from 0 to 9

str() str(123) Converts the integer value to a string

int() int("123") Converts the string value to an integer

float() float(123) Converts the integer value to a floating-point number

max() max(1, 2, 3, 4, 5) Returns the maximum value in the list of numbers

min() min(1, 2, 3, 4, 5) Returns the minimum value in the list of numbers

sorted() sorted([3, 2, 1]) Sorts the list in ascending order

type() type("Python") Returns the type of the object as “str”

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

abs() abs(-10) Returns the absolute value of the number

round() round(3.14159, 2) Rounds the number to 2 decimal places

Returns the character corresponding to the ASCII code 65, which is


chr() chr(65)
“A”
USER-DEFINED FUNCTIONS.

A User-Defined Function (UDF) is a function created by the user to


perform specific tasks in a program. Unlike built-in functions provided by
a programming language, UDFs allow for customization and code
reusability, improving program structure and efficiency.
syntax example

def function_name(parameters): def fun( x ):


# Function body if (x % 2 == 0):
return result print("even")
else:
print("odd")

fun(2)
Type Definition Example Output Explanation

Functions that accept def fun(name): The parameter name is replaced


1. Parameterized
parameters (arguments) for print("Hello,", name) Hello, shakshi by "shakshi" when the function
Functions
dynamic processing. fun("shakshi") is called.

def fun(x, y=50):


A function can assign
2. Functions with Default print("x:", x) x: 10 Since no value is given for y, it
default values to
Arguments print("y:", y) y: 50 takes the default value 50.
parameters.
fun(10)

Arguments are passed with def fun(name, age):


3. Keyword Argument Values are mapped explicitly to
keywords, regardless of print(name, "is", age, "years old.") shakshi is 21 years old.
Functions parameters using keywords.
order. fun(age=21, name="shakshi")

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)

Anonymous, single-line res = lambda x: x * x A one-line function that returns


6. Lambda Functions 16
functions using lambda. print(res(4)) the square of x.
MODULE IN PYTHON

A Python module is a file containing Python code, saved with a .py


extension. It serves as a container for organizing related code, such as
functions, classes, and variables, into a single, reusable unit.
Key characteristics of Python modules:
Code Organization:
Modules provide a way to logically group related code, making large
programs more manageable and easier to understand.
Reusability:
Code defined within a module can be imported and used in other
Python scripts or modules, promoting code reuse and reducing
redundancy.
Import Mechanism:
Modules are accessed using the import statement, which makes their
contents available for use in the importing script or module.
CREATING MODULE

Step 1: Create a file [Link]

# [Link]
def add(a, b):
return a + b
def subtract(a, b):
return a - b

Step 2: Import and use it in another file [Link]

import mymodule # importing Addition: 15


the module Subtraction: 5
print("Addition:",
[Link](10, 5))
print("Subtraction:",
[Link](10, 5))
BUILT-IN MODULE

Importing built-in Module

Built-in modules can be directly imported using "import" keyword without


any installtion. This allows access to all the functions and variables
defined in the module.

import math Value of pi: 3.141592653589793


pie = [Link]
print("Value of pi:", pie)

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

Importing External Modules

To use external modules, we need to install them first, we can easily


install any external module using pip command in the terminal, for
example:

pip install module_name import pandas


# Create a simple DataFrame
data = {
pip install pandas
"Name": ["Elon", "Trevor", "Swastik"],
"Age": [25, 30, 35]
Name Age }
0 Elon 25
1 Trevor 30 df = [Link](data)
2 Swastik 35 print(df)
EXTERNAL MODULES

Importing Specific Functions

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.

from math import pi


print(pi)

Importing Modules with Aliases


To make code more readable and concise, we can assign an alias to a
module using as keyword. This is especially useful when working with
long module names.
EXTERNAL MODULES

import math as m
result = [Link](25)
print("Square root of 25:", result)

Square root of 25: 5.0

Importing Everything from a Module (*)


Instead of importing specific functions, we can import all functions and
variables from a module using the * symbol. This allows direct access to
all module contents without prefixing them with the module name.

from math import * 3.141592653589793


print(pi) # Accessing the constant 'pi' 720
print(factorial(6))
PYTHON STANDARD LIBRARIES (MATH,
RANDOM, TIME)
Python's standard library includes modules that provide essential
functionalities without requiring external installations. Among these are
math, random, and time, each serving distinct purposes:
1. math Module:

This module provides access to mathematical functions and constants. It


supports a wide range of operations, including:
Trigonometric functions: sin(), cos(), tan(), asin(), acos(), atan().
Logarithmic functions: log(), log10(), log2().
Power and root functions: pow(), sqrt().
Constants: pi (mathematical constant π), e (Euler's number).
MATH MODULE
import math
print([Link](25)) # Output: 5.0
print([Link]) # Output: 3.141592653589793

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

print([Link]()) # Output: Current time in seconds since the epoch


[Link](2) # Pauses execution for 2 seconds
print([Link]()) # Output: Current local time as a string
print([Link](0))

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)

You might also like