0% found this document useful (0 votes)
10 views52 pages

Python Functions and Methods Guide

Uploaded by

myth87654321
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)
10 views52 pages

Python Functions and Methods Guide

Uploaded by

myth87654321
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

Computer Science

CLASS-XII (Code No. 083)

DPS RKP Computer Science Department


Python Functions 1

2021-2022
Unit 1: Computational Thinking and Programming - 2
● Functions: types of function (built-in functions, functions defined in
module, user defined functions), creating user defined function,
arguments and parameters, function returning value(s), flow of
execution, scope of a variable (global scope, local scope)

DPS RKP Computer Science Department


2
Types of functions
Built-in functions Functions defined in User defined functions
modules
print() tuple() math sin() AnyThing()
input() list() cos() AnyCalc()

DPS RKP Computer Science Department


len() dict() sqrt() .
range() str() .
random random()
max() chr() .
randint()
min() type() randrange() .
sum() id() .
statistics
int() bin() .
float() oct() mean() .
mode()
bool() hex()
median()

3
String Methods
Method Description
capitalize() Returns the converted string with the first character in uppercase.
count() Returns the number of times a specified value occurs in a string
find() Searches the string for a specified value and returns the position of where it

DPS RKP Computer Science Department


was found
format() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it
was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
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 4
String Methods
Method Description
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string

DPS RKP Computer Science Department


lower() Converts a string into lower case
partition() Returns a tuple where the string is parted into three parts

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
strip() Returns a trimmed version of the string
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 5
Tuple Methods
Method Description

count() Returns the number of times a specified value occurs in a tuple


index() Searches the tuple for a specified value and returns the position of

DPS RKP Computer Science Department


where it was found

6
List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list

DPS RKP Computer Science Department


count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

7
Dictionary (dict) Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value

DPS RKP Computer Science Department


get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the
key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary 8
Creating a user defined function
def keyword Formal Parameter

def <Function Name>([<Parameters>]): Function Header


<Statement1>

DPS RKP Computer Science Department


<Statement2>
Function Body
<StatementN>
[<return> <Value>]
Actual Parameter

<Function Name>(<Parameters>) Function Call

<Var>=<Function Name>(<Parameters>) Function Call

Actual Parameter
9
Function
A function is a sequence of statements that performs some specific
computational task. A function is a named unit of the program, which can be
called in any part of the program. It helps to avoid again and again writing the
same set of statement for performing the same task on different set of

DPS RKP Computer Science Department


input/values.

In Python, def keyword is used to define a function.


def <Function Name>(<Parameter List>): def First(a,b,c):
<Statement1> print(2*a)
<Statement2>
: print(3*b)
<StatementN> print(c*"-")

10
Function - Order of execution MK
MD

2 6 def Wish():
3 7 print("Good") FUNCTION DEFINITION
4 8 print("Day")

DPS RKP Computer Science Department


Wish()
1
Wish() OUTPUT
5
print("*----*") Good
9
Day
FUNCTION CALLS Good
Day
*----*

11
Function - Order of execution MK
MD

def Wish(Msg):
print("=========") FUNCTION DEFINITION
print("Good",Msg)
OUTPUT

DPS RKP Computer Science Department


Wish("Morning")
Wish("Day") =========
Wish("Evening") Good Morning
=========
Wish("Night")
Good Day
=========
FUNCTION CALLS Good Evening
=========
Good Night
Note: Msg is a parameter in function Wish(), which is
accepting values from call as "Morning","Day",...
12
Function - Order of execution
X Wish("Evening")
X Wish("Night")
def Wish(Msg): OUTPUT

DPS RKP Computer Science Department


print("=========")
print("Good",Msg) Line 1
✓ Wish("Morning") NameError: name 'Wish'
Wish("Day") is not defined

Note: If you define function in any other part of the


program, it can be called and executed only by the
statements written after the point of its definition and so, it
is not considered as a good programming practice to define
function(s) randomly anywhere in the program. Ideally, it
should be defined in beginning of the program. 13
Find area of triangle using a function

def Area(a,b,c):
S=(a+b+c)/2
A=(S*(S-a)*(S-b)*(S-c))**0.5

DPS RKP Computer Science Department


print("Area:",A,"cm²")
Area(3,4,5)
OUTPUT
Area(5,12,13)
Area(7,24,25) Area: 6.0 cm²
Area: 30.0 cm²
Area: 84.0 cm²

14
Find area of triangle using a function

import math
def Area1(A,B,C):
S=(A+B+C)/2
return (S*(S-A)*(S-B)*(S-C))**0.5

DPS RKP Computer Science Department


def Area2(A,B,C):
S=(A+B+C)/2
return [Link](S*(S-A)*(S-B)*(S-C)) OUTPUT
a=3;b=4;c=5
print(a,b,c,Area1(a,b,c),"cm²") 3 4 5 6.0 cm²
print(a,b,c,Area2(a,b,c),"cm²") 3 4 5 6.0 cm²

15
Display scholar message using a function

def Scholar(Marks):
if Marks>90:
print("Scholarship Granted")

DPS RKP Computer Science Department


else:
print("Re-appear for the Test")
Scholar(92) OUTPUT
Scholar(87)
M=int(input("Marks:")) Scholarship Granted
Scholar(M) Re-appear for the Test
Marks:98
Scholarship Granted

16
Display grades for marks using a function
def Grader(Marks):
if Marks>=90:
print("Marks:",Marks,"Grade A")
elif Marks>=75:

DPS RKP Computer Science Department


print("Marks:",Marks,"Grade B")
elif Marks>=60: OUTPUT
print("Marks:",Marks,"Grade C")
elif Marks>=50: Marks of Student1:96
print("Marks:",Marks,"Grade D") Marks: 96 Grade A
else: Marks of Student2:55
print("Marks:",Marks,"Grade E") Marks: 55 Grade D
M1=int(input("Marks of Student1:"))
Grader(M1)
M2=int(input("Marks of Student2:"))
Grader(M2) 17
Display line of string using a function

def Line(N,CH):
if N>2:
print(N*CH)
else:

DPS RKP Computer Science Department


print("Line can not be drawn")
Line(8,"#") OUTPUT
Line(1,"&")
Line(5,"*") ########
Line can not be drawn
*****

18
Display ride name for given Age using a function

def Ride(Age):
if Age>60:
print("Slow N Smooth Swinger")

DPS RKP Computer Science Department


elif Age>45:
print("Round, Stop N Round")
elif Age>25: OUTPUT
print("Up and Down Hopper")
Slow N Smooth Swinger
elif Age>10:
Kids Ride
print("Fast Track Ride")
Fast Track Ride
else:
Up and Down Hopper
print("Kids Ride")
Ride(67);Ride(5)
Ride(21);Ride(38)

19
Display box using functions
OUTPUT *******
def Line(N,CH): * *
print(N*CH) * *
*******

DPS RKP Computer Science Department


def Box(H,CH,W):
##########
Line(W,CH) # #
if H>1: ##########
for I in range(H-2):
print(CH) if W==1 else print(CH+(" "*(W-2))+CH)
Line(W,CH)
Box(4,"*",7)
Box(3,"#",10)

20
Display table of T, N times using function
def Table(T,N):
for I in range(1,N+1):
print(T*I,end=",")

DPS RKP Computer Science Department


print()
OUTPUT
Table(3,4)
Table(5,10) 3,6,9,12,
5,10,15,20,25,30,35,40,45,50,
Table(7,5)
7,14,21,28,35,

21
Display a sequence using function
def Seq(Start,End,Step):
print(end="Sequence:")
for I in range(Start,End+1,Step):

DPS RKP Computer Science Department


print(I,end=",")
print()
Seq(2,21,3)
Seq(7,70,10) OUTPUT

Sequence:2,5,8,11,14,17,20,
Sequence:7,17,27,37,47,57,67,

22
Immutable parameter in function

def Calc(A,B):
A=A*2
B=B+1

DPS RKP Computer Science Department


print("Calc:",A,B)
P,Q=100,200
print(P,Q)
Calc(P,Q)
OUTPUT
print(P,Q)
100 200
Calc: 200 201
100 200

23
Mutable parameter in function (List)

def Calc(A):
A[0]=A[0]*2
A[1]=A[1]+1

DPS RKP Computer Science Department


print("Calc:",A)
P=[100,200]
print(P)
Calc(P)
OUTPUT
print(P)
[100, 200]
Calc: [200, 201]
[200, 201]

24
Immutable parameter in function (Tuple)
def Calc(A):
A=list(A)
A[0]=A[0]*2

DPS RKP Computer Science Department


A[1]=A[1]+1
print("Calc:",A)
P=(100,200)
print(P)
OUTPUT
Calc(P)
print(P) (100, 200)
Calc: [200, 201]
(100, 200)

25
Mutable parameter in function (Dictionary)

def RaiseMarks(S,P):
S["Marks"]*=((100+P)/100)
S["Status"]="Changed"

DPS RKP Computer Science Department


S1={"Rno":1,"Name":"Raj","Marks":75,"Status":"*"}
S2={"Rno":3,"Name":"Ken","Marks":60,"Status":"*"}
RaiseMarks(S1,5)
RaiseMarks(S2,10)
print(S1)
print(S2)

OUTPUT

{'Rno': 1, 'Name': 'Raj', 'Marks': 78.75, 'Status': 'Changed'}


{'Rno': 3, 'Name': 'Ken', 'Marks': 66.0, 'Status': 'Changed'}
26
Mutable/immutable data objects

class description mutable immutable

bool Boolean value

DPS RKP Computer Science Department


int integer

float floating point number (Real Nos.)

tuple immutable sequence of objects

str Sequence of unicode characters

list mutable sequence of objects

dict dictionary (Associated Mapping)

27
Scope of identifiers L E G B
BUILTINS
print() input() len() type() id() B 4
GLOBAL
id=25 G 3

DPS RKP Computer Science Department


ENCLOSING
def First():
E 2
id=35;print(id) # 35
LOCAL
def Second():
L 1
id=45;print(id) # 45

Second()
First();print(id) # 25 28
MK
Name (also called Names used as Names used as MD
identifier) is simply a identifiers in a function
identifiers on top of a
name given to objects. (may be enclosed inside
Python Code another)
Everything in Python is an
object. Name is a way to
access it in Python code. G L

DPS RKP Computer Science Department


3 1
BUILTIN ENCLOSING
SCOPE
GLOBAL LOCAL
4 2
B E
Names already reserved by Python for Names used as identifiers in enclosing
specific purpose come under builtins function in a Python Code

29
Scope of variables/objects in Python program

G=10
def Test1():
G=20

DPS RKP Computer Science Department


print("Test1:",G)
def Test2():
G=30 OUTPUT
print("Test2:",G)
print("Main:",G) Main: 10
G+=5 Test1: 20
Test1() Main: 15
print("Main:",G) Test2: 30
G+=10 Main: 25
Test2()
print("Main:",G)
30
Returning results from Function

INPUT TO FUNCTION CALLING FUNCTION


THROUGH PARAMETERS WITH return

DPS RKP Computer Science Department


def Expression(A,B): print(Expression(2,3))
C=A+2*B A=10;B=25
return C C=Expression(A,B)
print(C)

OUTPUT FROM FUNCTION OUTPUT


THROUGH return
8
60
31
Calculate and return Area from function

def Area(a,b,c):
S=(a+b+c)/2
A=(S*(S-a)*(S-b)*(S-c))**0.5

DPS RKP Computer Science Department


return A
F1=Area(3,4,5)
F2=Area(5,12,13)
F3=Area(7,24,25)
print("Total Area:",F1+F2+F3,"cm²")

OUTPUT

Total Area: 120.0 cm²

32
Calculate and return Simple Interest from function

def SI(P,R,T):
return P*R*T/100
print("Interest:",SI(5000,10,3))

DPS RKP Computer Science Department


p,r,t=4000,5,4
si=SI(p,r,t)
amt=p+si
print("Interest:",si,"Amt to be paid:",amt)

OUTPUT

Interest: 1500.0
Interest: 800.0 Amt to be paid: 4800.0

33
Calculate and return ITax & Allowance from functions
def ITax(Basic):
if Basic<70000:
return Basic*0.1
else:

DPS RKP Computer Science Department


return Basic*0.3 OUTPUT
def Allowance(Basic):
if Basic<50000: Basic:60000
return Basic*0.4 ITax: 6000.0 Allowance: 30000.0
else: Salary In hand: 84000.0
return Basic*0.5
BS=float(input("Basic:"))
IT=ITax(BS);AL=Allowance(BS)
INHAND=BS-IT+AL
print("ITax:",IT,"Allowance:",AL)
print("Salary In hand:",INHAND) 34
Calculate and return Grade from function
def Grader(Marks):
if Marks>=90:
return "A"
elif Marks>=75:

DPS RKP Computer Science Department


return "B" OUTPUT
elif Marks>=60:
return "C" Marks of Student 1:78
elif Marks>=50: Student 1 Marks: 78 Grade: B
return "D" Marks of Student 2:99
else: Student 2 Marks: 99 Grade: A
return "E"
M1=int(input("Marks of Student 1:"))
print("Student 1 Marks:",M1,"Grade:",Grader(M1))
M2=int(input("Marks of Student 2:"))
print("Student 2 Marks:",M2,"Grade:",Grader(M2)) 35
Swap the 1st and 2nd half of list using function
def HalfSwap(L):
n=len(L)
for i in range(n//2):
L[i],L[n//2+i]=L[n//2+i],L[i]

DPS RKP Computer Science Department


A=[10,20,30,40,50,60,70]
print(A)
HalfSwap(A)
print(A) OUTPUT
A=[12,34,56,65,43,23]
print(A) [10, 20, 30, 40, 50, 60, 70]
HalfSwap(A) [40, 50, 60, 10, 20, 30, 70]
print(A) [12, 34, 56, 65, 43, 23]
[65, 43, 23, 12, 34, 56]

36
Swap the alternate elements of list using function
def SwapAlternate(L):
N=len(L)
for i in range(0,N-1,2):
L[i],L[i+1]=L[i+1],L[i]

DPS RKP Computer Science Department


A=[10,20,30,40,50,60,70]
print(A)
SwapAlternate(A)
print(A) OUTPUT
A=[12,34,56,65,43,23]
print(A) [10, 20, 30, 40, 50, 60, 70]
SwapAlternate(A) [20, 10, 40, 30, 60, 50, 70]
print(A) [12, 34, 56, 65, 43, 23]
[34, 12, 65, 56, 23, 43]

37
def Something(SomeParameter):
#Some Expressions
Var1=SomeParameter*5
Var2=SomeParameter*3
return Var1,Var2

DPS RKP Computer Science Department


P=input("Some Value:")
Multi Values return V1,V2=Something(P)
print(V1)
The function can return print(V2)
multiple values also
OUTPUT
Some Value:Hello
HelloHelloHelloHelloHello
HelloHelloHello

38
Display benefits according to designations

def Benefits(Desig):
if Desig=="D":
C="BMW";H="BUNGLOW"

DPS RKP Computer Science Department


elif Desig=="M" or Desig=="E":
C="CIAZ";H="MIG"
elif Desig=="A":
C="DZIRE";H="LIG" OUTPUT
else:
D:Director M:Manager E:Executive A:Accountant=E
C="NA";H="NA"
return C,H CIAZ MIG
DC=input("D:Director M:Manager E:Executive A:Accountant=")
c,h=Benefits(DC) Assigning results of function to a 2 str variables
print(c,h)
39
Display benefits according to designations

def Benefits(Desig):
if Desig=="D":
C="BMW";H="BUNGLOW"

DPS RKP Computer Science Department


elif Desig=="M" or Desig=="E":
C="CIAZ";H="MIG"
elif Desig=="A":
C="DZIRE";H="LIG" OUTPUT
else:
D:Director M:Manager E:Executive A:Accountant=D
C="NA";H="NA"
return C,H ('BMW', 'BUNGLOW')
DC=input("D:Director M:Manager E:Executive A:Accountant=")
c=Benefits(DC)
print(c) Assigning results of function as a tuple
40
Returning list from a function

def Scholars(L):
S=[]
for i in L:

DPS RKP Computer Science Department


if i>90:
[Link](i) OUTPUT
return S
L1=[67,98,45,92] L1: [67, 98, 45, 92]
L2=[95,58,95,99,87] Sclr Marks from L1: [98, 92]
SLR1=Scholars(L1) L2: [95, 58, 95, 99, 87]
SLR2=Scholars(L2) Sclr Marks from L2: [95, 95, 99]
print("L1:",L1)
print("Sclr Marks from L1:",SLR1)
print("L2:",L2)
print("Sclr Marks from L2:",SLR2)
41
Returning dictionary from a function

def Scholars(ST):
S={}
for k,v in [Link]():

DPS RKP Computer Science Department


if v>=90:
S[k]=v
return S
S1={"Anu":67,"Raj":98,"Ken":45,"Ram":92}
SR1=Scholars(S1)
print(S1) OUTPUT
print(SR1)
{'Anu': 67, 'Raj': 98, 'Ken': 45, 'Ram': 92}
{'Raj': 98, 'Ram': 92}

42
Accessing value of a global variable inside a function
G=10
def Test():
L=G+20 # Local Var

DPS RKP Computer Science Department


print("Local:",L) OUTPUT
print("Main:",G) Main: 10
G+=30 Local: 60
Test() Main: 40

print("Main:",G)

43
Modifying global variable inside a function
"Int" IMMUTABLE type cannot be
G=100 modified inside function1
def Function1():
G+=20

DPS RKP Computer Science Department


print(G) OUTPUT
print(G)
G+=10 100
print(G) 110
Function1() ---------------
print(G) UnboundLocalError

44
Modifying global variable inside a function
"int" global keyword
G=100
required for immutable type
def Function1():
global G

DPS RKP Computer Science Department


G+=20
print(G)
print(G) OUTPUT
G+=10
print(G) 100
Function1() 110
130
print(G)
130

45
Modifying global variable inside a function
"list" global keyword not
G=[100,200]
required for mutable type
def Raise(R):
G[0]+=R;G[1]+=R

DPS RKP Computer Science Department


print("After Raise:",G)
print("Main:",G)
r=10 OUTPUT

Raise(r) Main: [100, 200]


print("Main:",G) After Raise: [110, 210]
Main: [110, 210]

46
Modifying global variable inside a function
"dict" global keyword not
G={"Tap":75,"Ram":82}
required for mutable type
def Raise(R):
G["Tap"]+=R;G["Ram"]+=R

DPS RKP Computer Science Department


print("After Raise:",G)
print("Main:",G)
r=10 OUTPUT

Raise(r) Main: {'Tap': 75, 'Ram': 82}


print("Main:",G) After Raise: {'Tap': 85, 'Ram': 92}
Main: {'Tap': 85, 'Ram': 92}

47
Compare the codes

i=90 i=90
def test(j): def test():
j+=90 global i

DPS RKP Computer Science Department


i+=90
print(j)
print(i)
test(i) test()
print(i) print(i)

OUTPUT OUTPUT

180 180
90 180

48
Compare the codes

i=[90,100]
i=[90,100]
def test(j):
def test():
j[0]+=10;j[1]+=10

DPS RKP Computer Science Department


i[0]+=10;i[1]+=10
print(j) print(i)
test(i) test()
print(i)
print(i)

OUTPUT OUTPUT

[100, 110] [100, 110]


[100, 110] [100, 110]

49
Quick Questions
● Can we have same name for a Global object, which pre-exists as built in? YES

● Can we have same name for a Local object, which pre-exists as Global? YES

DPS RKP Computer Science Department


● Can local scope use the same name for Global and local? NO

● Can we access global object inside a function without using global keyword? YES

● Can we modify global object containing immutable value inside a function NO


without using global keyword?
● As we have, global keyword, do we have a keyword with name local too? NO

● Can we use the word global as a name for our own variable as identifier? NO

50
Quick sum up - Function - 1
Function
[Link]
● is a named unit of a program
● definition starts with def keyword def Func1():
● can contain a sequence of steps required for a particular task

DPS RKP Computer Science Department


● may have parameter(s) of any mutable/immutable type def Func2():
● may return results in/of any type Func2()
● can be called any number of times in the program Func1()
● Statements will not get executed unless function is called Func2()
● Can be defined in any part of program, but ideally should be in the
beginning of the program
● Can contain another function within, but it will be used within the
scope of enclosing function only

51
Happy Learning…

DPS RKP Computer Science Department


Thank you!
Department of Computer Science

52

You might also like