0% found this document useful (0 votes)
4 views

Python Ch-4_Notes

This document provides an overview of functions in Python, including their definitions, types (built-in and user-defined), and advantages such as code reusability and easier debugging. It explains how to define functions, the difference between parameters and arguments, and various types of function arguments. Additionally, it covers variable scope, the Python standard library, and the use of input and output functions.

Uploaded by

hetshihora247
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)
4 views

Python Ch-4_Notes

This document provides an overview of functions in Python, including their definitions, types (built-in and user-defined), and advantages such as code reusability and easier debugging. It explains how to define functions, the difference between parameters and arguments, and various types of function arguments. Additionally, it covers variable scope, the Python standard library, and the use of input and output functions.

Uploaded by

hetshihora247
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
You are on page 1/ 15

Python Programming (UNIT-4) | 4311601

Unit-IV: Functions (Marks-16)


Introduction to Functions
 A function is a group of logically related statements that is used to perform specific task.
 Functions provides facility of re-usability: It means once a function is defined and tested it
can be used any number of times in program.
Python provide two type of function:
1. Built-in function: A function which is already define in standard library of python is
known as Built in function.
2. User define function: A function which is define by user to perform specific task is
known as User define function.
Advantages of Python Functions
 There is no need to write same code again and again. So it reduce the length of program.
 Once defined, Python functions can be called multiple times and from any location in a
program.
 Our Python program can be broken up into many, easy-to-follow functions if it is required.
 Error handling and Debugging becomes easy because whenever an error is occurred you
have to debug only function’s statements
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation string
of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 1


Python Programming (UNIT-4) | 4311601
Syntax
def function_name( parameters ):
“ Function docstring”
Function_suite
return [expression]

Example:
def my_function(): # function header
print("Hello from a function")
# calling function from main code
my_function()
O/P:
Hello from a function
Example:
def my_function(fname):
print(Hello", fname)
my_function("ABC")
my_function("XYZ")
my_function("DEF")
O/P:
Hello ABC
Hello XYZ
Hello DEF
Arguments
 Information can be passed into functions as arguments.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 2
Python Programming (UNIT-4) | 4311601
 Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
Parameters vs. Arguments
 Sometimes, parameters and arguments are used interchangeably. It’s important to
distinguish between the parameters and arguments of a function.
 A parameter is a piece of information that a function needs. And you specify the
parameter in the function definition. For example, the greet() function has a parameter
called name.
 An argument is a piece of data that you pass into the function. For example, the text
string 'John' or the variable jane is the function argument.
Example:
def greet(name): #parameter
print('Hi')
greet(“John”) #argument
Types of Function Arguments
You can call a function by using the following types of formal arguments −
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments/ Arbitrary Arguments
1. Required arguments
 Required arguments are the arguments passed to a function in correct positional order.
 Here, the number of arguments in the function call should match exactly with the function
definition.
Example:
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
#function call
function( 30, 20 )
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 3
Python Programming (UNIT-4) | 4311601
O/P:
number 1 is: 30
number 2 is: 20
2. Keyword arguments
 Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
 You can also send arguments with the key = value syntax.
 This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
Example:
# Function definition is here
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)

# Now you can call printinfo function


printinfo( age=50, name="miki" )
O/P:
Name: miki
Age 50
3. Default arguments
 A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.
 If we call the function without argument, it uses the default value
Example:
# Function definition is here
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)

# Now you can call printinfo function


INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 4
Python Programming (UNIT-4) | 4311601
printinfo( age=50, name="miki" )
printinfo( name="miki" )
O/P:
Name: miki
Age 50
Name: miki
Age 35
4. Variable-length arguments/ Arbitrary Arguments
 You may need to process a function for more arguments than you specified while
defining the function.
 These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
Syntax:
def functionname([formal_args,] *var_args_tuple ):
function_suite
return [expression]
Example:
# Function definition is here
def printinfo( arg1, *vartuple ):
# "This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
O/P:
Output is:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 5
Python Programming (UNIT-4) | 4311601
10
Output is:
70
60
50
The return Statement/Value
 The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
 When a defined function is called, a return statement is written to exit the function and
return the calculated value.
Syntax:
return < expression to be returned as output >
Example:
# Defining a function with return statement
def square( num ):
return num**2

# Calling function and passing arguments.


print( "With return statement" )
print( square( 52 ) )
O/P:
With return statement
2704
Difference between User-Defined Function and Library Function

S.No. User-Defined Functions Library Functions

These functions are created by users These functions are not created by
1 as per their own requirements. users as their own.

User-defined functions are not stored Library Functions are stored in a


2 in library files. special library file.

3
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 6
Python Programming (UNIT-4) | 4311601
There is no such kind of requirement If the user wants to use a particular
to add a particular module/ packages. library function then the user has to
add the module/ packages

There is no error because they are


4 Possibility of error
pre-compiled

UDF is the part of program which is Library functions are the part of
5 compiled at run time program which is called at run time

6 Example: sum(), fact(),…etc. Example: int(),float(),str()…etc

Scope of a Variable
 A variable is only available from inside the region it is created. This is called scope.
 The location where we can find a variable and also access it if required is called the scope
of a variable.
In Python, we can declare variables in two different scopes: local scope, global scope.
Based on the scope, we can classify Python variables into two types:
1. Local Variables
2. Global Variables
1. Local Variables
 When we declare variables inside a function, these variables will have a local scope
(within the function). We cannot access them outside the function.
 These types of variables are called local variables.
Example:
def myfunc():
x = 300
print(x)
print(x) #cannot access outside the function
myfunc()
O/P:
300
2. Global Scope

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 7


Python Programming (UNIT-4) | 4311601
 A variable created in the main body of the Python code is a global variable and belongs to
the global scope.
 Global variables are the ones that are defined and declared outside any function and are
not specified to any function
 Global variables are available from within any scope, global and local.
Example:
x = 300
def myfunc(): #function defination
print(x)
myfunc() #function call
print(x) # can use anywhere in program
O/P:
300
300
Python standard library
 The Python Standard Library contains the exact syntax, semantics, and tokens of Python.
It contains built-in modules that provide access to basic system functionality like I/O and
some other core modules.
 Most of the Python Libraries are written in the C programming language. The Python
standard library consists of more than 200 core modules.
 All these work together to make Python a high-level programming language. Python
Standard Library plays a very important role. Without it, the programmers can’t have
access to the functionalities of Python.
Let’s have a look at some of the commonly used libraries:
1. TensorFlow: It is an open-source library used for high-level computations. It is also
used in machine learning and deep learning algorithms. It contains a large number of
tensor operations.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why it
is used in data analysis. It is also an open-source library and plots high-defined figures
like pie charts, histograms, scatterplots, graphs, etc.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 8


Python Programming (UNIT-4) | 4311601
3. Pandas: Pandas are an important library for data scientists. It is an open-source
machine learning library that provides flexible high-level data structures and a variety
of analysis tools.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly
used library. It is a popular machine learning library that supports large matrices and
multi-dimensional data.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library
used for high-level scientific computations. This library is built over an extension of
Numpy.
6. PyGame: This library provides an easy interface to the Standard Direct media Library
(SDL) platform-independent graphics, audio, and input libraries. It is used for
developing video games using computer graphics and audio libraries along with
Python programming language.
7. Scrapy: It is an open-source library that is used for extracting data from websites. It
provides very fast web crawling and high-level screen scraping. It can also be used for
data mining and automated testing of data.
8. BeautifulSoup: It has an excellent XML and HTML parsing library for beginners.
Use of Libraries in Python Program
 As we write large-size programs in Python, we want to maintain the code’s modularity.
For the easy maintenance of the code, we split the code into different parts and we can
use that code later ever we need it.
 In Python, modules play that part. Instead of using the same code in different programs
and making the code complex, we define mostly used functions in modules and we can
just simply import them in a program wherever there is a requirement.
 We don’t need to write that code but still, we can use its functionality by importing its
module. Multiple interrelated modules are stored in a library.
 And whenever we need to use a module, we import it from its library. In Python, it’s a
very simple job to do due to its easy syntax. We just need to use import.

Python input() and output() Function


1. Python input()
 Python input() function is used to get input from the user.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 9


Python Programming (UNIT-4) | 4311601
 It prompts for the user input and reads a line. After reading data, it converts it into a string
and returns that.
Syntax:
input ([prompt])
prompt: It is a string message which prompts for the user input.
Example:
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
O/P:
Enter a value: 45
You entered: 45
2. output() Function
 In Python, we can simply use the print() function to print output.
Syntax:
print(value)
 value(s) : Any value, and as many as you like. Will be converted to string before printed
Example:
print("GFG")
print('G', 'F', 'G')
O/P:
GFG
GFG
Python Mathematical Functions
A function which is already define in standard library of python is known as Built in
function.

N Name Description Syntax Example


o
1 It return an absolute value of abs(number) abs(5) = 5
abs()
the number, number can be abs(-2.5) = 2.5
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 10
Python Programming (UNIT-4) | 4311601
integer or float
2 divmod( It accepts two numbers of divmod(no1, no2) divmod(5, 2) = (2,1)
) type integer or floating point divmod(2.5, 2) =
as an arguments and return a (1.0,0.5)
tuple containing quotient
and reminder
3 max() It accepts two numbers of max(no1, no2) max(2, 5, -1, 3.5)= 5
type integer or floating point max([ 55, -11,
as an arguments and return a 30.5])= 55
maximum number among
them
4 min() It accepts two numbers of min(no1, no2) max(2, 5, -1, 3.5)= -1
type integer or floating point max([ 55, -11,
as an arguments and return a 30.5])= -11
minimum number among
them
5 pow() It accepts two numbers of pow(n01, n02) pow(2,3)= 8
type integer or floating point pow(n01, n02, no3) pow(2,3,4)=0
as an arguments and return
values that is no1 raised to
power of no2.
It has one optional
argument. If it specified than
it return (no1 no2)%no3

6 sum() It accepts a sequence of type sum([n1,n2,n3…n] sum([2,3,4,5])=14


integer or floating point as )
an arguments and return
sum of all elements of
sequence from left to right
7 round() It accepts two numbers of round(no) round(20.522)= 21
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 11
Python Programming (UNIT-4) | 4311601
type floating point as an round(no, round(5.4)= 5
arguments and return decimal_point) round(5.4567,2)=
rounded number. 5.46
It has one optional argument round(5.4327,2)=
to specify number of 5.43
decimal to use while
rounding the number.
8 len() It accepts a sequence or len([1,2,3,4]) len(‘hello’)=5
dictionary as an argument len([1,2,3,4])=4
and return count which len({1:”A”,2:”B”})=2
indicates number of
elements of sequence or
dictionary

Module
 A Python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables.
 A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use. It also makes the code logically organized.
 Modules are provide the facility of reusability .
 In python two types of modules are their:
1. Built in Module (Standard Library Modules): A module which is already created in
standard library of python is known as Built in Module.
2. User Define Module: A module which is created by user is known as User Define
Module.
Math Module:
Python has a built-in module that you can use for mathematical tasks.
The math module has a set of methods and constants.
Sr Function Use Example
.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 12


Python Programming (UNIT-4) | 4311601
N
o
Rounds a number up to the nearest math.ceil(2.3) =3
1 math.ceil()
integer math.ceil(2.7) =3
Rounds a number down to the nearest math.floor(2.3)=2
2. math.floor()
integer math.floor((2.7)=2
3. math.exp() Returns E raised to the power of x math.exp(2)=7.389056
math.fabs(-4) =4
4 math.fabs() Returns the absolute value of a number
math.fabs(-4.3)=4.3
5 math.fmod Returns the remainder of x/y math.fmod(4,3)=1
math.factorial(
6 Returns the factorial of a number math.factorial(5)=120
)
Returns the sum of all items in any math.fsum([1,2,3,4,5])=15.
7 math.fsum()
iterable (tuples, arrays, lists, etc.) 0
Returns the greatest common divisor
8 math.gcd() math.gcd(12,8)= 4
of two integers
Returns the value of x to the power of
9 math.pow() math.pow(2,3) = 8
y

Math Constants
Sr.
Constant Description
No
1 math.e() Returns Euler's number (2.7182...)
2 math.pi() Returns PI (3.1415...)

Random Module
Python Random module is an in-built module of Python that is used to generate random
numbers in Python.
These numbers occur randomly and does not follow any rules or instructuctions.
We can therefore use this module to generate random numbers, display a random item for a
list or string, and so on.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 13
Python Programming (UNIT-4) | 4311601
Sr.
Function Use Example
No
1 random.random( Generate random floating numbers random.random()=
) between 0 to 1 0.4585545764414376
2 random.randint() Returns a random integer within the random.randint(1,50)=
range 22
Example:
import random
print(random.random())
print(random.random())
print(random.randint(5,50))
O/P:
0.050357716811645026
0.8258126187037218
49

Statistic Module
Python has a built-in module that you can use to calculate mathematical statistics of numeric
data.
Sr.
Function Use Example
No
1 statistics.mean() Calculates the mean statistics.mean([1,2,3,4,5,6])=
(average) of the given data 3.5
2 statistics.mode() return the mode (most repeated statistics.mode([1,2,3,2,5,5])=
value) of the given data 2
3 statistics.median( Calculates the median (middle statistics.median([1,2,3,4,5,6])
) value) of the given data =
3.5
4 statistics.stdev() Calculates the standard statistics.stdev([1,2,3,4,5,6])=
deviation from a sample of 1.8708286933869707
data
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 14
Python Programming (UNIT-4) | 4311601

Example:
import statistics
print(statistics.mean([1,2,3,4,5,6]))
print(statistics.mode([1,2,3,2,5,5]))
print(statistics.median([1,2,3,4,5,6]))
print(statistics.stdev([1,2,3,4,5,6]))
O/P:
3.5
2
3.5
1.8708286933869707

**********

“Do not give up, the beginning is always hardest!”

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 15

You might also like