0% found this document useful (0 votes)
32 views21 pages

Python Functions and Modules Guide

Tybsc Python Programmimg Unit 5

Uploaded by

Pradh Mahajan
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)
32 views21 pages

Python Functions and Modules Guide

Tybsc Python Programmimg Unit 5

Uploaded by

Pradh Mahajan
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

DNCVP COLLEGE, JALGAON

DEPARTMENT OF COMPUTER SCIENCE


(Academic Year 2025–26)

CS-505 PYTHON PROGRAMMING-I

Prepared By: Asst. Prof. Pradnya Mahajan


TY BSc Computer Science – 2025–26

1
UNIT 5

Python Functions and Modules


✓ Introduction to Python: History of Python.
✓ Version of Python..
✓ Need, Features of Python.
✓ Applications of Python.
✓ Installing Python on Linux and Windows.
✓ Installing Python IDE

2
Introduction to functions:

A function is a group of related statements that performs a specific task. A function is a block of code which only runs when it is called. You can
pass data, known as parameters, into a function. A function can return data as a result. It is also known as procedure or subroutine in other
programming languages.

Defining a function:

Function can be defined using a 'def keyword. Function block is started with a color(:). All the same level block statements are remain at the
same indentation.

Syntax:

def function_name():

statement/s

return <expression>

e.g.

def hello():

print("Hello, Welcome in Python function")

e.g.

def hello1():

name = "Python"
3
return(name)

Calling a Function:

A function must be defined before the function calling, otherwise the python interpreter gives error. Once the function is defined, we can call it
from another function or the python prompt. To call the function, use the function name followed by the parentheses.

Syntax:

def function_name():

statement/s

return <expression>

function_name()

e.g.

def Hello():

print("Hello Python!")

Hello()

e.g.

hello():

name = "Python"

4
return(name)

print("Hello", hello())

Function Arguments:

Information can be passed into functions as arguments. Parameters are specified after the function name, inside the parentheses. Any number of
arguments can be added in parentheses separated by comma. A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called. There are several types of arguments which can be passed at the time of
function calling:

1. Required arguments

2. Keyword arguments

3. Default arguments

4. Variable-length arguments

1. Required Arguments:

Required arguments are passed at the time of function calling. They should be match their positions in function call with function
definition. If either of argument is not provided in the function call, or if argument position is changed, then the python interpreter shows
an error.

e.g. argument with constants

def sum(a,b)

5
sum=a+b

return(sum)

num1=100

num2=200

print(sum(numl,num2))

e.g. argument with input()

def sum(a,b):

sum=a+b

return(sum)

num1 = int(input("Enter first number:")

num2 = int(input("Enter second number:"))

print(sum(num1, num2))

e.g. argument with input :

When the function is called, we passed a name, which used inside the function to print name.

def fun_hello(name):

message = "Hello"+name

6
return(message)

name = input("Enter your name:")

print(fun_hello(name))

2. Keyword argument:
Python allows us to send arguments with the key = value syntax. This kind of function call enables us to pass the arguments in the
random order. The name of argument is treated as the keywords and matched in the function calling and definition. If the same match is
found, the values of the arguments are copied in the function definition.

e.g. keyword argument


def fun_welc(message, name):
print(message, "to", name, "!")
fun_welc(name="Python", message="Welcome")
e.g. argument with input()
def sum(a,b,c)
retum(a+b+c)
print("Sum is:", sum(b=3,a=7,c=9))
3. Default Argument:
If the value of any of the argument is not provided at the time of the function call, then that argument can be initialized with the value
given in the definition even if the argument is not specified at the function call.
e.g. argument with input()

7
def welcome(name, address="SSVPS, Dhule"):
print("I am", name, "Studying in", address)
welcome(name="Manisha")
4. Variable Length argument:
Python provides us the flexibility to provide the comma separated values which are internally treated as tuples at the function call.
However, at the function definition, we have to define the variable with * (star) as <variable-name>
e.g. function with arguments
def printme(names):
print("type of passed argument is ", type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("C", "C+t","Java","Python")

Scope of Variables:
The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the
program may not be accessible to the other parts. In python, the variables are defined with the two types of scopes. Global variableLocal
variables. The variable defined outside any function is known to have a global scope whereas the variable defined inside a function is
known to have a local [Link] tuples at the function call.
e.g.
def printmsg(name): name="Metlab"

8
print("Name in local Scope ",name) printmsg(name) #Local Scope name="Python"
print("Name in Global Scope ",name) #Global Scope
Void functions:
A function that just executes. It can accepts arguments. It does not "return" a value.
e.g.
def hello():
print("Hello World!")
hello()
Output: Hello World!
e.g.
def sum(a):
print(a+5)
sum(5)
Output: 10
Function Returning Values:
A function that just executes. It accepts arguments. It return a value or values.
e.g.
def hello(name):
msg="Hello "+ name + ", Welcome to Python Programming!"
return(msg)
result hello("Arhan")
print(result)

9
#Function return single value
e.g.
def sum(a,b):
sum=a+b
return(sum)
result=sum(10,20))
print(result)
#Output: 30
#Function with multiple return values
e.g.
def getdimensions():
length= float(input("Enter the Length"))
width= float(input("Enter the Width"))
return length, width
1, w= getdimensions()
print(1,w)
Output: Enter the Length 20
Enter the Width 30
20.0 30.0

10
Recursion:
Python also accepts function recursion, which means a defined function can call [Link] is a common mathematical and
programming concept. It means that a function calls itself. When recursion functions are written correctly, it can be a very efficient and
mathematically-elegant approach to programming.

e.g.
def tri_recursion(k):
if(k > 0)
result = k + tri_recursion(k-1)
print(result)
else:
result =0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
In this example, tri_recursion() is a function that we have defined to call itself ("recursion"). We every time of recursion. The
recursion ends use the k variable as the data, which decrements (-1) when the condition is not greater than 0 (i.e. when it is 0).
Anonymous Function Lambda :
A function without name is called Anonymous Function. It is also known as Lambda Function. Here def keyword is not required rather,
defined using lambda keyword. It returns a function [not required return statement]. It contain expressions and can't include statements in
body. It take one or more arguments : expression. Lambda functions can be used along with built-in functions like filter(), map() and
reduce().

11
e.g.
hello- lambda x:
print(x)
hello("Hello")
#Output: Hello
Normal function using def keyword
def square(a):
print(aa)
square(5)
#Output: 25
Lambda function
square lambda x:
print(square(5))
#Output: 25
add_sub = lambda x, y :
(x+y,x−y)
a, s=add_sub(300,200)
print(a)
print(s)
#Output: 500 100

12
Mapping Function :
map() function returns a map object(which is an iterator) of the results. After applying the given function to each item of a given iterable
(list, tuple etc.).
Syntax:
map(function_name, iterable)
e.g.
def square(n):
return n*n
numbers =(1,2,3,4)
result = map(square, numbers)
print(list(result))
Output: [1, 4, 9, 16]
Lambda with map :
e.g.
temps=[("India",35),("Berlin",29),("Tokyo",27),("London",22)]
f= lambda data: (data[0], (9/5)*data[1]+32)
print(list(map(c_to_f,temps)))
Output: [('India', 95.0), ('Berlin', 84.2), ('Tokyo', 80.6), ('London', 71.6)]
Lambda with filter:
filter() function takes a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence "sequence",
for which the function returns True.

13
e.g.
mylist=[1,2,3,4,5,6,7,8,9,10]
even_list = list(filter(lambda x: (x, mylist))
print(even_list)
#Output: [2, 4, 6, 8, 10]
filter() function used to remove missing data:
e.g.
mylist=["","India","","Berlin","","","London","","Tokyo"]
print(list(filter(None,mylist)))
#Output: ['India', 'Berlin', 'London', 'Tokyo']
Lambda with reduce: The reduce() function takes a function and a list as argument. The function is called with a lambda function and a
list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list.
Syntax:
reduce(lambda_function, list/tuple)
e.g.
from functools import reduce
mylist=[1,2,3,4,5,6,7,8,9,10]
sum = reduce((lambda x,y: (x+y)),
mylist)
print(sum)
#Output:55

14
Introduction to Module:
A module is to be the same as a code library. A file containing a set of functions you want to include in your application. A module is a
file containing Python definitions and statements. A module can define functions, classes and variables. A module can also include
runnable code.
Creating Modules and Packages :
To create a module just save the code you want in a file with the file [Link]
Example: Write the following and save file on [Link] and execute it.

e.g.
def greeting(name):
print("Hello, " + name)
How to Use Module:
To create a module just save the code you want in a file with the file extension. The save module import the python file [Link]
e.g.
import mymodule
[Link]("Rohan")
Packages:
A package is a collection of Python modules. A package is a directory of Python. A package from a directory contains a bunch of Python
scripts. We can use 'packages as follows: Create a new folder named E:\MyApp. Inside MyApp, create a subfolder with the name
'MyPack'. Create an empty_init_.py file in the "MyPack" folder. Using a Python-aware editor like IDLE, create modules [Link] and
[Link]

15
e.g.
from MyPack import functions
[Link](4,2)
Output: 16
e.g.
from MyPack import greet
[Link]("Rohan")
Output: Hello Rohan
e.g.
from [Link]
import div div(500,5)
Output: 100.0
Why to use_init__.py The package folder contains a special file called init_.py, which stores the package's content. It serves two
purposes:
[Link] Python interpreter recognizes a folder as the package if it contains init_.py file.
[Link] exposes specified resources from its modules to be imported
dir(): The dir() is a built-in function. It returns a sorted list of strings containing the names defined by a module. List contains the names
of all the modules, variables and functions that are defined in a module.
Built-in modules : A large number of pre-defined functions are also available as a part of libraries bundled with Python distributions.
These functions are defined in modules. A module is a file containing definitions of functions, classes, variables, constants or any other
Python objects. Contents of this file can be made available to any other program. There are several built-in modules in Python, which you
can import whenever you like. They are loaded automatically as the interpreter starts and are always available. For example, input() and

16
print() are for input and output, number conversion can be done with functions like int(), float(), complex() while data type conversions
can be perform using list(), tuple(), set() etc.
e.g.
import platform x= [Link]()
print(x)
Output: windows
OS Module:
It is possible to automatically perform many operating system tasks. The OS module in Python provides functions for creating and
removing a directory (folder), fetching Its contents, changing and identifying the current directory, etc.
Creating Directory: We can create a new directory using the mkdir() function from the OS module.
e.g.
import os
[Link]("e:\tempdir")
A new directory corresponding to the path in the string argument of the function will be created. If we open E drive in Windows Explorer,
we should notice tempdir folder created.

Changing the Current Working Directory :

We must first change the current working directory to a newly created one before doing any operations in it. This is done using the
chdir() function.

17
e.g.
import os
[Link]("e:\tempdir")
There is a getcwd() function in the OS module using which we can confirm if the current working directory has been changed or not.
e.g.
[Link]()
#Output: 'e:\tempdir'
math module: Some of the most popular mathematical functions are defined in the math module. These include trigonometric functions,
representation functions, logarithmic functions, angle conversion functions, etc. In addition, two mathematical constants are also defined
in this module. Pie ( ) is a well-known mathematical constant, which is defined as the ratio of the circumference to the diameter of a
circle and its value is 3.141592653589793.
e.g.
import math
[Link]()
Output: 3.141592653589793
Another well-known mathematical constant defined in the math module is e. It is called Euler's number and it is a base of the natural
logarithm. Its value is 2.718281828459045.
e.g.
math.e()
Output: 2.718281828459045
The math module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan, etc.) need
the angle in radians as an argument used to measure angle. The math module presents two angle conversion functions: degrees() and

18
radians(), to convert the angle from degrees to radians and vice versa. The following statements convert the angle of 30 degrees to
radians and back (Note: π radians is equivalent to 180 degrees).
e.g.
[Link](30)
Output: 0.5235987755982988

e.g.
[Link]([Link]/6)
Output: 29.9999999996
The following statements shows sin, cos and tan ratios for the angle of 30 degrees (0.5235987755982988 radians):
e.g.
[Link](0.5235987755982988)
Output: 0.4999999999999994
[Link](0.5235987755982988)
Output: 0.8660255037844387
[Link](0.5235987755982988)
Output: 0.5773502691896257
[Link]():The [Link]() method returns the natural logarithm of a given number. The natural logarithm is calculated to the base e.
e.g.
[Link](10)
Output: 2.302585092994046
math.log10(): The math.log10() method returns the base-10 logarithm of the given number. It is called the standard logarithm.

19
e.g.
math.log10(10)
Output: 1.0
[Link]():
The [Link]() method returns a float number after raising e (math.e) to given number. In other words, exp(x) gives e**x.

e.g.
[Link](1.0)
Output: 2.718281828459045
[Link](): The [Link]() method receives two float arguments, raises the first to the second and returns the result. In other words,
pow(4,4) is equivalent to 44.
e.g.
[Link](2,3)
Output: 8.0
e.g.
2**4
Output: 16
[Link](): The [Link]() method returns the square root of a given number.
e.g.
[Link](100)
Output: 10.0

20
e.g.
[Link](49)
Output: 7.0
[Link](): The ceil() function approximates the given number to the smallest integer, greater than or equal to the given floating point
number.
e.g.
[Link](5.6875)
Output: 5
[Link](): The floor() function returns the largest integer less than or equal to the given number.
e.g.
[Link](5.6875)
Output: 5

21

You might also like