SlideShare a Scribd company logo
FUNCTIONS
Function Introduction
A function is a subprogram that acts on data and often returns a value
OR
A function is a programming block of codes which is used
1. to perform a single, related task.
2. It only runs when it is called.
3. We can pass data/value, known as parameters, into a function.
4. A function can return data as a result.
Advantages of Using Functions:
1.Program development made easy and fast : Work can be divided among
project members thus implementation can be completed fast.
2. Program testing becomes easy
3. Code sharing becomes possible
4.Code re-usability increases
5. Increases program readability
6.Function facilitates procedural abstraction : Once a function is written,
it serves as a black box. All that a programmer would have to know to invoke a
function would be to know its name, and the parameters that it expects
7.Functions facilitate the factoring of code : A function can be called in
other function and so on…
• Built –in functions (function using Libraries)
• Functions defined in the modules(function using Libraries)
• User defined functions
Types of Functions
Built-in functions
Pre-defined functions that are always available
for use.
e.g.
print() ,len() ,input() ,ord() ,hex() ,type(), int() etc
String functions:
Method Description
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
partition() Returns a tuple where the string is parted into three parts
Functions using libraries(System defined function or Built- in Functions)
Syntax:
stringname.functionname()
e.g.
a.isupper()
String functions:
Method Description Syntax
capitalize() Converts the first character to upper case str.capitalize()
center() string padded with specified fillchar. str.center(width,[fillchar])
#Width means length of the string
count() Returns the number of times a specified value
occurs in a string
str.count(substring,[start], [end])
endswith() Returns true if the string ends with the
specified value
str.endswith(substring,[start],[end])
format() Formats specified values in a string print("Hello {}, your rollno {}.".format(“abc", 23))
print("Hello {name}, your rollno {rn}.“
.format(name=“abc", rn=23))
find()
Searches the string for a specified value and
returns the position(index) of where it was
found
str.find(sub,[start],[end] )
index()
Searches the string for a specified value and
returns the position of where it was found
str.index(sub,[start],[end] )
The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception.
Functions using libraries(System defined function or Built- in Functions)
String functions:
Method Description
replace()
Returns a string where a specified value is replaced with a
specified value
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Functions using libraries(System defined function or Built- in Functions)
Functions defined in modules
Pre-defined functions that are in particular
modules and can only be used when
corresponding module is imported.
e.g.
import math
sin(), cos(),abs(),floor() etc
Modules
Modules
• is a part of a program
• used for dividing up the program into smaller, more easily
understood, reusable parts.
A module is a file containing
1. Python definitions and statements.
2. Module can define functions, classes and variables.
3. A module can also include runnable code.
4. Grouping related code into a module makes the code easier to
understand and use.
Functions using libraries/ Functions defined in Modules
Mathematical functions:
Mathematical functions are available under math module.To use
mathematical functions under this module, we have to import the
module using import math.
For e.g.
To use sqrt() function we have to write statements like given below.
import math
r=math.sqrt(4)
print(r)
OUTPUT :
2.0
Functions available in Python Math Module
Functions using libraries(Functions defined in Modules)
User defined functions
These are defined by the programmer according
to his/her requirements /needs.
Creating a Function (user defined)
A function is defined using the def keyword in
python.
def <function_name>([arguments/parameters]):
[“”” function’s docstring “””]
<statement>
[statement]
[statement]
:
:
Function block/ definition/ working of the function
def fun():
print("Hello")
print(“world”)
e.g.
Syntax: Name of the function
colon at the end means it requires a block
def
means
function
definition
is starting
arguments/parameters-means values given to function
def cals(a):
b=2*a
print(b)
Few terms : Defining functions
• Function header- first line of the function that begins with the
keyword def and end with the (:) colon. It specifies the name of the
function and its parameters
• Parameters-values that are listed within the parentheses of a
function header
• Indentation- blank space in the beginning of a statement within a
block. All statements within the block have same indentation.
Calling a Function(user defined)
Syntax:
def Function_name(arguments/parameters):
statements
#program start here.program code
print("hello before calling a function")
fun(3) #function calling.now function codes will be executed
print("hello after calling a function")
def fun(a):
print(“hello”,a)
Function definition
4 Parts To Create User Defined Functions
•Function definition
•Arguments(those variables which
are use in function calling)
•Parameters(those variables which
are use in function definition)
•Function Calling
Flow of execution in function Calling
• 1 def fun(a,b):
• 2 c=a+b
• 3 print(c)
• 4 x=2
• 5 y=4
• 6 fun(x,y)
1-4-5-6-1-2-3
void functions- those functions which are not
returning values to the calling function
Flow of execution in function Calling
• 1 def fun(a,b):
• 2 c=a+b
• 3 return c
• 4 x=int(input())
• 5 y= int(input())
• 6 z=fun(x,y)
• 7 print(z)
1-4-5-6-1-2-3-6-7
Non void functions- those functions which are
returning values to the calling function
Flow of execution in function Calling
1.def fun(a,b):
2. c=a+b
3. print(c)
4. return
5.x=2
6.y=4
7.z=fun(x,y)
8.print(z)
1-5-6-7-1-2-3-4-8
Void functions- those functions which are not
returning values to the calling function.
We may use return but it will return none value to the
function call
Void functions and Non void functions
def fun(a,b):
c=a+b
print(c)
return
x=2
y=4
z=fun(x,y)
print(z)
We may use return but it will
return none value to the
function call
def fun(a,b):
return a+b, a, 5
x=2
y=4
z,w,q=fun(x,y)
print(z,w,q)
Output
6
None
Output
6 2 5
Value return can be literal,variable ,
expression
Arguments/Parameters
def fun(a,b):
c=a+b
print(c)
x=2
y=4
fun(x,y) #variables
fun(5,6) #literals
fun(x+3,y+6) #expressions
Arguments- passed values in function call.
It can be of three types
1. Literals
2. Variables
3. Expressions
Arguments
Arguments/Parameters
def fun(a,b): #parameters
c=a+b
print(c)
x=2
y=4
fun(x,y)
Parametes- received values in function
definition.
It should be of variable types.
Returning Multiple Values from Functions
def fun(a,b):
return a+b,a-b
x=2
y=4
z=fun(x,y)
print(z)
1. Received values as tuple
2. Unpack received values as tuple
def fun(a,b):
return a+b,a-b
x=2
y=4
d,z=fun(x,y)
print(d,z)
def fun(x,y): #Parameters- variables used in function definition - should be of variable type here x and y are parameters
z=x+y
return z, z**3 ,5 #function can return values in the form of variable, expression, literal
#function calling
a=int(input("enter no1")) #1 a=4
b=int(input("enter no2")) #2 b=5function calling
q=fun(a,b) #variable type arguments (values which are used in function calling)
print(q)
t=fun(3,5) #literal type arguments here 3 and 5 are literal type arguments
print(t)
z=fun(a+3,b+4) #expression type arguments
print(z)
‘’’
Output
enter no1 5
enter no2 6
(11, 1331, 5)
(8, 512, 5)
(18, 5832, 5)
‘’’
Here output is in the form of tuples
becoz function is returning multiple
values and we r storing them in single
variable
Returning Values from Functions
four possible combinations as functions
def fun():
a=2
b=3
print(a,b)
fun()
1. Void functions without arguments
2. Void functions with arguments
def fun(a,b):
print(a+b)
x=2
y=3
fun(x,y)
Returning Values from Functions
four possible combinations as functions
def fun():
a=2
b=3
return(a,b)
c=fun()
print(c)
3. Non Void functions without arguments
4. Non Void functions with arguments
def fun(a,b):
return(a+b)
x=2
y=3
c=fun(x,y)
print(c)
Types of Arguments
def fun(a,b):
c=a+b
print(c)
x=10
y=3
fun(x,y)
fun(x,y,z) #wrong no of arguments passed
1. Positional parameters(Required Arguments) - these arguments
must be provided for all parameters
Types of Arguments
def fun(a,b,c=3):
d=a+b+c
print(d)
x=10
y=3
fun(x,y) #here c parameter value is 3
z=5
fun(x,y,z) #here it will be take parameter c value as 5
2. Default Arguments- if right parameter have default value then left parameters can
also have default value. this argument can be skipped at the time of function calling
Types of Arguments
def fun(a,b,c):
print(a,b,c)
a=1
b=3
c=5
fun(b,c,a)
3. Keyword Arguments(Named Arguments)- We can write arguments in any
order but we must give values according to their name
Output
3 5 1
def fun(a,b,c):
print(a,b,c)
fun(b=3,c=4,a=2)
Output
2 3 4
Scope of Variables
Scope means –to which extent a code or data would be known or accessed.
There are three types of variables with the view of scope.
1. Global Scope- Name declared in main program . It is usable inside the whole
program.
def fun(a,b):
s = a+b
print(s)
X=int(input(“enter no1”))
Y=int(input(“enter no2”))
fun(X,Y)
#here X and Y are global variable
def fun(a):
s = a+Y
retrun(s)
X=10
Y=20
Z=fun(X,Y)
Print(Z)
#here X and Y are global variable
Scope of Variables
Scope means –to which extent a code or data would be known or accessed.
1. Local Scope- Name declared in function body. It is usable within the function.
def fun():
A=10
B=20
return(A+B)
C=fun()
print(C)
print(A)
#here A and B are local variables and C is
global varibale
Variable’s Scope in function
.
1. Non local variable – accessible in nesting of functions,using nonlocal keyword.
def fun1():
x = 100
def fun2():
nonlocal x #change it to global or remove this declaration
x = 200
print("Before calling fun2: " + str(x))
print("Calling fun2 now:")
fun2()
print("After calling fun2: " + str(x))
x=50
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 200
x in main: 50
Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among whole program using
global keyword.
3. Non local variable – accessible in nesting of functions,using nonlocal keyword.
Local variable program:
def fun():
s = "I love India!" #local variable
print(s)
s = "I love World!"
fun()
print(s)
Output:
I love India!
I love World!
Global variable program:
def fun():
global s #accessing/making global variable for fun()
print(s)
s = "I love India!“ #changing global variable’s value
print(s)
s = "I love world!"
fun()
print(s)
Output:
I love world!
I love India!
I love India!
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun1(x,y):
s=x+y
print(num1)
return s
num1=100
num2=200
sm=fun1(num1,num2)
print(sm)
.
Variable in global scope not in local scope
CASE 1
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun():
print(“hello”,n)
fun()
#
Output:
Name error: name ‘n’ is
not defined
.
Variable neither in in local scope nor in global scope
CASE 2
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun():
a=10
print(a)
a=5
print(a)
fun()
print(a)
# output
5
10
5
.
Variable name in local scope as well as in global scope
CASE 3
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun():
global a
a=10
print(a)
a=5
print(a)
fun()
print(a)
# output
5
10
10
.
Using global variable inside local scope
This case is discouraged in
good programming
CASE 4
Function
Parameters / Arguments
These are specified after the function name, inside the parentheses. Multiple
parameters are separated by comma.The following example has a function with
two parameters x and y. When the function is called, we pass two values, which
is used inside the function to sum up the values and store in z and then return
the result(z):
def sum(x,y): #x, y are formal arguments
z=x+y
return z #return the result
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
Note :- 1. Function Prototype is declaration of function with name
,argument and return type.
2. A formal parameter, i.e. a parameter, is in the function definition. An
actual parameter, i.e. an argument, is in a function call.
Function Arguments
Functions can be called using following types of formal arguments −
• Required arguments - arguments passed to a function in correct positional order
• Keyword arguments - the caller identifies the arguments by the parameter name
• Default arguments - that assumes a default value if a value is not provided to argu.
#Required arguments/Positional arguments
def square(x):
z=x*x
return z
print(square(3)
#In above function square() we have to definitely need to
pass some value
#Keyword arguments
def fun( name, age ):
print (name,age)
return;
fun( age=15, name="mohak" )
# value 15 and mohak is being passed to
relevant argument based on keyword used for them.
#Default arguments
def sum(x=3,y=4):
z=x+y
return z
r=sum() #default value of x and y is being used when it is not passed
print(r)
r=sum(x=4)
print(r)
r=sum(y=45)
print(r)
Mutable/Immutable properties of data w/r function
Everything in Python is an object,and every objects in Python can be
either mutable or immutable.
Since everything in Python is an Object, every variable holds an object
instance. When an object is initiated, it is assigned a unique object id. Its
type is defined at runtime and once set can never change, however its
state can be changed if it is mutable.
Means a mutable object can be changed after it is created, and an
immutable object can’t.
Mutable objects: list, dict, set, byte array
Immutable objects: int, float, complex, string, tuple, frozen set ,bytes
Passing Immutable type values to a function
e.g.
def fun(a):
print(a)
a=a+2
print a
n=3
print(n)
fun(n)
print(n)
Output
3
3
5
3
Passed value of n remains unchanged because it is immutable
Passing mutable type value to a function
e.g.
def fun(a):
print(a)
a[0]=1
print (a)
n=[3,5,6]
print(n)
fun(n)
print(n)
Output
3,5,6
3,5,6
1,5,6
1,5,6
Value changed in function change the value in main program(because list
change values at same address and only single value is changing)
CASE-1
Passing mutable type value to a function
e.g.
def fun(a):
print(a)
f=[7,8]
a=f
print (a)
n=[3,5,6]
print(n)
fun(n)
print(n)
Output
3,5,6
3,5,6
7,8
3,5,6
Value changed in function did not change for main program(because a is
assigned a whole new list not a change of single values for whole
program
CASE-2
Pass Mutable type values to a function
Arrays are popular in most programming languages like: Java, C/C++, JavaScript and
so on. However, in Python, they are not that common. When people talk about Python
arrays, more often than not, they are talking about Python lists. Array of numeric
values are supported in Python by the array module.
e.g.
def dosomething( thelist ):
for element in thelist:
print (element)
dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )
OUTPUT:
1
2
3
red
green
Blue
Note:- List is mutable datatype that’s why it treat as pass by reference.It is
already explained in topic Mutable/immutable properties of data objects w/r
function
Mutable/immutable properties of data objects w/r function
How objects are passed to Functions
#Pass by reference
def updateList(list1):
print(id(list1))
list1 += [10]
print(id(list1))
n = [50, 60]
print(id(n))
updateList(n)
print(n)
print(id(n))
OUTPUT
34122928
34122928
34122928
[50, 60, 10]
34122928
#In above function list1 an object is being passed
and its contents are changing because it ismutable
that’s why it is behaving like pass by reference
#Pass by value
def updateNumber(n):
print(id(n))
n += 10
print(id(n))
b = 5
print(id(b))
updateNumber(b)
print(b)
print(id(b))
OUTPUT
1691040064
1691040064
1691040224
5
1691040064
#In above function value of variable b is not
being changed because it is immutable that’s
why it is behaving like pass by value

More Related Content

PDF
Python revision tour II
PDF
Revised Data Structure- STACK in Python XII CS.pdf
PPTX
Chapter 02 functions -class xii
PDF
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
PPTX
11 Unit1 Chapter 1 Getting Started With Python
PPTX
11 Unit 1 Chapter 02 Python Fundamentals
PDF
Python-02| Input, Output & Import
PPTX
Chapter 16 Dictionaries
Python revision tour II
Revised Data Structure- STACK in Python XII CS.pdf
Chapter 02 functions -class xii
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
11 Unit1 Chapter 1 Getting Started With Python
11 Unit 1 Chapter 02 Python Fundamentals
Python-02| Input, Output & Import
Chapter 16 Dictionaries

What's hot (20)

PDF
Python revision tour i
PPTX
DATA STRUCTURE CLASS 12 .pptx
PPTX
Chapter 08 data file handling
PPTX
Python Functions
PPTX
Relational Database.pptx
PDF
Python functions
PPTX
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
PDF
Character Array and String
PPTX
Types of function call
PPTX
Strings in c++
PPTX
Computer System Overview Class XI CS
PDF
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
PPTX
Functions in C
PDF
C Programming Storage classes, Recursion
PPTX
Array operations
PPT
Stacks
PPTX
Inline function
PPTX
Call by value or call by reference in C++
PDF
Python file handling
PPTX
Arrays in c
Python revision tour i
DATA STRUCTURE CLASS 12 .pptx
Chapter 08 data file handling
Python Functions
Relational Database.pptx
Python functions
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
Character Array and String
Types of function call
Strings in c++
Computer System Overview Class XI CS
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
Functions in C
C Programming Storage classes, Recursion
Array operations
Stacks
Inline function
Call by value or call by reference in C++
Python file handling
Arrays in c
Ad

Similar to Chapter Functions for grade 12 computer Science (20)

PDF
Functions-.pdf
DOCX
Functions.docx
PDF
2-functions.pptx_20240619_085610_0000.pdf
PDF
Functions2.pdf
PPTX
Python Details Functions Description.pptx
PPTX
Python_Functions_Modules_ User define Functions-
PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
PPTX
Python for Data Science function third module ppt.pptx
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
PPTX
functions.pptx
PPTX
Functions in python
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
PPTX
Python functions PYTHON FUNCTIONS1234567
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
Functions and Modules.pptx
PPTX
Python Lecture 4
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PDF
Dive into Python Functions Fundamental Concepts.pdf
PPTX
Functions_new.pptx
PPTX
FUNCTIONINPYTHON.pptx
Functions-.pdf
Functions.docx
2-functions.pptx_20240619_085610_0000.pdf
Functions2.pdf
Python Details Functions Description.pptx
Python_Functions_Modules_ User define Functions-
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
Python for Data Science function third module ppt.pptx
cbse class 12 Python Functions2 for class 12 .pptx
functions.pptx
Functions in python
function_xii-BY APARNA DENDRE (1).pdf.pptx
Python functions PYTHON FUNCTIONS1234567
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
Functions and Modules.pptx
Python Lecture 4
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
Dive into Python Functions Fundamental Concepts.pdf
Functions_new.pptx
FUNCTIONINPYTHON.pptx
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Institutional Correction lecture only . . .
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Classroom Observation Tools for Teachers
PPTX
Lesson notes of climatology university.
PPTX
GDM (1) (1).pptx small presentation for students
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
human mycosis Human fungal infections are called human mycosis..pptx
Institutional Correction lecture only . . .
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Types and Its function , kingdom of life
Classroom Observation Tools for Teachers
Lesson notes of climatology university.
GDM (1) (1).pptx small presentation for students
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
TR - Agricultural Crops Production NC III.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
VCE English Exam - Section C Student Revision Booklet
O7-L3 Supply Chain Operations - ICLT Program
Complications of Minimal Access Surgery at WLH
Module 4: Burden of Disease Tutorial Slides S2 2025
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
FourierSeries-QuestionsWithAnswers(Part-A).pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial disease of the cardiovascular and lymphatic systems

Chapter Functions for grade 12 computer Science

  • 2. Function Introduction A function is a subprogram that acts on data and often returns a value OR A function is a programming block of codes which is used 1. to perform a single, related task. 2. It only runs when it is called. 3. We can pass data/value, known as parameters, into a function. 4. A function can return data as a result.
  • 3. Advantages of Using Functions: 1.Program development made easy and fast : Work can be divided among project members thus implementation can be completed fast. 2. Program testing becomes easy 3. Code sharing becomes possible 4.Code re-usability increases 5. Increases program readability 6.Function facilitates procedural abstraction : Once a function is written, it serves as a black box. All that a programmer would have to know to invoke a function would be to know its name, and the parameters that it expects 7.Functions facilitate the factoring of code : A function can be called in other function and so on…
  • 4. • Built –in functions (function using Libraries) • Functions defined in the modules(function using Libraries) • User defined functions Types of Functions
  • 5. Built-in functions Pre-defined functions that are always available for use. e.g. print() ,len() ,input() ,ord() ,hex() ,type(), int() etc
  • 6. String functions: Method Description isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case lower() Converts a string into lower case lstrip() Returns a left trim version of the string partition() Returns a tuple where the string is parted into three parts Functions using libraries(System defined function or Built- in Functions) Syntax: stringname.functionname() e.g. a.isupper()
  • 7. String functions: Method Description Syntax capitalize() Converts the first character to upper case str.capitalize() center() string padded with specified fillchar. str.center(width,[fillchar]) #Width means length of the string count() Returns the number of times a specified value occurs in a string str.count(substring,[start], [end]) endswith() Returns true if the string ends with the specified value str.endswith(substring,[start],[end]) format() Formats specified values in a string print("Hello {}, your rollno {}.".format(“abc", 23)) print("Hello {name}, your rollno {rn}.“ .format(name=“abc", rn=23)) find() Searches the string for a specified value and returns the position(index) of where it was found str.find(sub,[start],[end] ) index() Searches the string for a specified value and returns the position of where it was found str.index(sub,[start],[end] ) The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception. Functions using libraries(System defined function or Built- in Functions)
  • 8. String functions: Method Description replace() Returns a string where a specified value is replaced with a specified value split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning Functions using libraries(System defined function or Built- in Functions)
  • 9. Functions defined in modules Pre-defined functions that are in particular modules and can only be used when corresponding module is imported. e.g. import math sin(), cos(),abs(),floor() etc
  • 10. Modules Modules • is a part of a program • used for dividing up the program into smaller, more easily understood, reusable parts. A module is a file containing 1. Python definitions and statements. 2. Module can define functions, classes and variables. 3. A module can also include runnable code. 4. Grouping related code into a module makes the code easier to understand and use.
  • 11. Functions using libraries/ Functions defined in Modules Mathematical functions: Mathematical functions are available under math module.To use mathematical functions under this module, we have to import the module using import math. For e.g. To use sqrt() function we have to write statements like given below. import math r=math.sqrt(4) print(r) OUTPUT : 2.0
  • 12. Functions available in Python Math Module Functions using libraries(Functions defined in Modules)
  • 13. User defined functions These are defined by the programmer according to his/her requirements /needs.
  • 14. Creating a Function (user defined) A function is defined using the def keyword in python. def <function_name>([arguments/parameters]): [“”” function’s docstring “””] <statement> [statement] [statement] : : Function block/ definition/ working of the function def fun(): print("Hello") print(“world”) e.g. Syntax: Name of the function colon at the end means it requires a block def means function definition is starting arguments/parameters-means values given to function def cals(a): b=2*a print(b)
  • 15. Few terms : Defining functions • Function header- first line of the function that begins with the keyword def and end with the (:) colon. It specifies the name of the function and its parameters • Parameters-values that are listed within the parentheses of a function header • Indentation- blank space in the beginning of a statement within a block. All statements within the block have same indentation.
  • 16. Calling a Function(user defined) Syntax: def Function_name(arguments/parameters): statements #program start here.program code print("hello before calling a function") fun(3) #function calling.now function codes will be executed print("hello after calling a function") def fun(a): print(“hello”,a) Function definition
  • 17. 4 Parts To Create User Defined Functions •Function definition •Arguments(those variables which are use in function calling) •Parameters(those variables which are use in function definition) •Function Calling
  • 18. Flow of execution in function Calling • 1 def fun(a,b): • 2 c=a+b • 3 print(c) • 4 x=2 • 5 y=4 • 6 fun(x,y) 1-4-5-6-1-2-3 void functions- those functions which are not returning values to the calling function
  • 19. Flow of execution in function Calling • 1 def fun(a,b): • 2 c=a+b • 3 return c • 4 x=int(input()) • 5 y= int(input()) • 6 z=fun(x,y) • 7 print(z) 1-4-5-6-1-2-3-6-7 Non void functions- those functions which are returning values to the calling function
  • 20. Flow of execution in function Calling 1.def fun(a,b): 2. c=a+b 3. print(c) 4. return 5.x=2 6.y=4 7.z=fun(x,y) 8.print(z) 1-5-6-7-1-2-3-4-8 Void functions- those functions which are not returning values to the calling function. We may use return but it will return none value to the function call
  • 21. Void functions and Non void functions def fun(a,b): c=a+b print(c) return x=2 y=4 z=fun(x,y) print(z) We may use return but it will return none value to the function call def fun(a,b): return a+b, a, 5 x=2 y=4 z,w,q=fun(x,y) print(z,w,q) Output 6 None Output 6 2 5 Value return can be literal,variable , expression
  • 22. Arguments/Parameters def fun(a,b): c=a+b print(c) x=2 y=4 fun(x,y) #variables fun(5,6) #literals fun(x+3,y+6) #expressions Arguments- passed values in function call. It can be of three types 1. Literals 2. Variables 3. Expressions Arguments
  • 23. Arguments/Parameters def fun(a,b): #parameters c=a+b print(c) x=2 y=4 fun(x,y) Parametes- received values in function definition. It should be of variable types.
  • 24. Returning Multiple Values from Functions def fun(a,b): return a+b,a-b x=2 y=4 z=fun(x,y) print(z) 1. Received values as tuple 2. Unpack received values as tuple def fun(a,b): return a+b,a-b x=2 y=4 d,z=fun(x,y) print(d,z)
  • 25. def fun(x,y): #Parameters- variables used in function definition - should be of variable type here x and y are parameters z=x+y return z, z**3 ,5 #function can return values in the form of variable, expression, literal #function calling a=int(input("enter no1")) #1 a=4 b=int(input("enter no2")) #2 b=5function calling q=fun(a,b) #variable type arguments (values which are used in function calling) print(q) t=fun(3,5) #literal type arguments here 3 and 5 are literal type arguments print(t) z=fun(a+3,b+4) #expression type arguments print(z) ‘’’ Output enter no1 5 enter no2 6 (11, 1331, 5) (8, 512, 5) (18, 5832, 5) ‘’’ Here output is in the form of tuples becoz function is returning multiple values and we r storing them in single variable
  • 26. Returning Values from Functions four possible combinations as functions def fun(): a=2 b=3 print(a,b) fun() 1. Void functions without arguments 2. Void functions with arguments def fun(a,b): print(a+b) x=2 y=3 fun(x,y)
  • 27. Returning Values from Functions four possible combinations as functions def fun(): a=2 b=3 return(a,b) c=fun() print(c) 3. Non Void functions without arguments 4. Non Void functions with arguments def fun(a,b): return(a+b) x=2 y=3 c=fun(x,y) print(c)
  • 28. Types of Arguments def fun(a,b): c=a+b print(c) x=10 y=3 fun(x,y) fun(x,y,z) #wrong no of arguments passed 1. Positional parameters(Required Arguments) - these arguments must be provided for all parameters
  • 29. Types of Arguments def fun(a,b,c=3): d=a+b+c print(d) x=10 y=3 fun(x,y) #here c parameter value is 3 z=5 fun(x,y,z) #here it will be take parameter c value as 5 2. Default Arguments- if right parameter have default value then left parameters can also have default value. this argument can be skipped at the time of function calling
  • 30. Types of Arguments def fun(a,b,c): print(a,b,c) a=1 b=3 c=5 fun(b,c,a) 3. Keyword Arguments(Named Arguments)- We can write arguments in any order but we must give values according to their name Output 3 5 1 def fun(a,b,c): print(a,b,c) fun(b=3,c=4,a=2) Output 2 3 4
  • 31. Scope of Variables Scope means –to which extent a code or data would be known or accessed. There are three types of variables with the view of scope. 1. Global Scope- Name declared in main program . It is usable inside the whole program. def fun(a,b): s = a+b print(s) X=int(input(“enter no1”)) Y=int(input(“enter no2”)) fun(X,Y) #here X and Y are global variable def fun(a): s = a+Y retrun(s) X=10 Y=20 Z=fun(X,Y) Print(Z) #here X and Y are global variable
  • 32. Scope of Variables Scope means –to which extent a code or data would be known or accessed. 1. Local Scope- Name declared in function body. It is usable within the function. def fun(): A=10 B=20 return(A+B) C=fun() print(C) print(A) #here A and B are local variables and C is global varibale
  • 33. Variable’s Scope in function . 1. Non local variable – accessible in nesting of functions,using nonlocal keyword. def fun1(): x = 100 def fun2(): nonlocal x #change it to global or remove this declaration x = 200 print("Before calling fun2: " + str(x)) print("Calling fun2 now:") fun2() print("After calling fun2: " + str(x)) x=50 fun1() print("x in main: " + str(x)) OUTPUT: Before calling fun2: 100 Calling fun2 now: After calling fun2: 200 x in main: 50
  • 34. Variable’s Scope in function There are three types of variables with the view of scope. 1. Local variable – accessible only inside the functional block where it is declared. 2. Global variable – variable which is accessible among whole program using global keyword. 3. Non local variable – accessible in nesting of functions,using nonlocal keyword. Local variable program: def fun(): s = "I love India!" #local variable print(s) s = "I love World!" fun() print(s) Output: I love India! I love World! Global variable program: def fun(): global s #accessing/making global variable for fun() print(s) s = "I love India!“ #changing global variable’s value print(s) s = "I love world!" fun() print(s) Output: I love world! I love India! I love India!
  • 35. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun1(x,y): s=x+y print(num1) return s num1=100 num2=200 sm=fun1(num1,num2) print(sm) . Variable in global scope not in local scope CASE 1
  • 36. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun(): print(“hello”,n) fun() # Output: Name error: name ‘n’ is not defined . Variable neither in in local scope nor in global scope CASE 2
  • 37. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun(): a=10 print(a) a=5 print(a) fun() print(a) # output 5 10 5 . Variable name in local scope as well as in global scope CASE 3
  • 38. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun(): global a a=10 print(a) a=5 print(a) fun() print(a) # output 5 10 10 . Using global variable inside local scope This case is discouraged in good programming CASE 4
  • 39. Function Parameters / Arguments These are specified after the function name, inside the parentheses. Multiple parameters are separated by comma.The following example has a function with two parameters x and y. When the function is called, we pass two values, which is used inside the function to sum up the values and store in z and then return the result(z): def sum(x,y): #x, y are formal arguments z=x+y return z #return the result x,y=4,5 r=sum(x,y) #x, y are actual arguments print(r) Note :- 1. Function Prototype is declaration of function with name ,argument and return type. 2. A formal parameter, i.e. a parameter, is in the function definition. An actual parameter, i.e. an argument, is in a function call.
  • 40. Function Arguments Functions can be called using following types of formal arguments − • Required arguments - arguments passed to a function in correct positional order • Keyword arguments - the caller identifies the arguments by the parameter name • Default arguments - that assumes a default value if a value is not provided to argu. #Required arguments/Positional arguments def square(x): z=x*x return z print(square(3) #In above function square() we have to definitely need to pass some value #Keyword arguments def fun( name, age ): print (name,age) return; fun( age=15, name="mohak" ) # value 15 and mohak is being passed to relevant argument based on keyword used for them. #Default arguments def sum(x=3,y=4): z=x+y return z r=sum() #default value of x and y is being used when it is not passed print(r) r=sum(x=4) print(r) r=sum(y=45) print(r)
  • 41. Mutable/Immutable properties of data w/r function Everything in Python is an object,and every objects in Python can be either mutable or immutable. Since everything in Python is an Object, every variable holds an object instance. When an object is initiated, it is assigned a unique object id. Its type is defined at runtime and once set can never change, however its state can be changed if it is mutable. Means a mutable object can be changed after it is created, and an immutable object can’t. Mutable objects: list, dict, set, byte array Immutable objects: int, float, complex, string, tuple, frozen set ,bytes
  • 42. Passing Immutable type values to a function e.g. def fun(a): print(a) a=a+2 print a n=3 print(n) fun(n) print(n) Output 3 3 5 3 Passed value of n remains unchanged because it is immutable
  • 43. Passing mutable type value to a function e.g. def fun(a): print(a) a[0]=1 print (a) n=[3,5,6] print(n) fun(n) print(n) Output 3,5,6 3,5,6 1,5,6 1,5,6 Value changed in function change the value in main program(because list change values at same address and only single value is changing) CASE-1
  • 44. Passing mutable type value to a function e.g. def fun(a): print(a) f=[7,8] a=f print (a) n=[3,5,6] print(n) fun(n) print(n) Output 3,5,6 3,5,6 7,8 3,5,6 Value changed in function did not change for main program(because a is assigned a whole new list not a change of single values for whole program CASE-2
  • 45. Pass Mutable type values to a function Arrays are popular in most programming languages like: Java, C/C++, JavaScript and so on. However, in Python, they are not that common. When people talk about Python arrays, more often than not, they are talking about Python lists. Array of numeric values are supported in Python by the array module. e.g. def dosomething( thelist ): for element in thelist: print (element) dosomething( ['1','2','3'] ) alist = ['red','green','blue'] dosomething( alist ) OUTPUT: 1 2 3 red green Blue Note:- List is mutable datatype that’s why it treat as pass by reference.It is already explained in topic Mutable/immutable properties of data objects w/r function
  • 46. Mutable/immutable properties of data objects w/r function How objects are passed to Functions #Pass by reference def updateList(list1): print(id(list1)) list1 += [10] print(id(list1)) n = [50, 60] print(id(n)) updateList(n) print(n) print(id(n)) OUTPUT 34122928 34122928 34122928 [50, 60, 10] 34122928 #In above function list1 an object is being passed and its contents are changing because it ismutable that’s why it is behaving like pass by reference #Pass by value def updateNumber(n): print(id(n)) n += 10 print(id(n)) b = 5 print(id(b)) updateNumber(b) print(b) print(id(b)) OUTPUT 1691040064 1691040064 1691040224 5 1691040064 #In above function value of variable b is not being changed because it is immutable that’s why it is behaving like pass by value