Python Functions and Methods Guide
Python Functions and Methods Guide
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)
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
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
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
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
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
10
Function - Order of execution MK
MD
2 6 def Wish():
3 7 print("Good") FUNCTION DEFINITION
4 8 print("Day")
11
Function - Order of execution MK
MD
def Wish(Msg):
print("=========") FUNCTION DEFINITION
print("Good",Msg)
OUTPUT
def Area(a,b,c):
S=(a+b+c)/2
A=(S*(S-a)*(S-b)*(S-c))**0.5
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
15
Display scholar message using a function
def Scholar(Marks):
if Marks>90:
print("Scholarship Granted")
16
Display grades for marks using a function
def Grader(Marks):
if Marks>=90:
print("Marks:",Marks,"Grade A")
elif Marks>=75:
def Line(N,CH):
if N>2:
print(N*CH)
else:
18
Display ride name for given Age using a function
def Ride(Age):
if Age>60:
print("Slow N Smooth Swinger")
19
Display box using functions
OUTPUT *******
def Line(N,CH): * *
print(N*CH) * *
*******
20
Display table of T, N times using function
def Table(T,N):
for I in range(1,N+1):
print(T*I,end=",")
21
Display a sequence using function
def Seq(Start,End,Step):
print(end="Sequence:")
for I in range(Start,End+1,Step):
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
23
Mutable parameter in function (List)
def Calc(A):
A[0]=A[0]*2
A[1]=A[1]+1
24
Immutable parameter in function (Tuple)
def Calc(A):
A=list(A)
A[0]=A[0]*2
25
Mutable parameter in function (Dictionary)
def RaiseMarks(S,P):
S["Marks"]*=((100+P)/100)
S["Status"]="Changed"
OUTPUT
27
Scope of identifiers L E G B
BUILTINS
print() input() len() type() id() B 4
GLOBAL
id=25 G 3
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
29
Scope of variables/objects in Python program
G=10
def Test1():
G=20
def Area(a,b,c):
S=(a+b+c)/2
A=(S*(S-a)*(S-b)*(S-c))**0.5
OUTPUT
32
Calculate and return Simple Interest from function
def SI(P,R,T):
return P*R*T/100
print("Interest:",SI(5000,10,3))
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:
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]
37
def Something(SomeParameter):
#Some Expressions
Var1=SomeParameter*5
Var2=SomeParameter*3
return Var1,Var2
38
Display benefits according to designations
def Benefits(Desig):
if Desig=="D":
C="BMW";H="BUNGLOW"
def Benefits(Desig):
if Desig=="D":
C="BMW";H="BUNGLOW"
def Scholars(L):
S=[]
for i in L:
def Scholars(ST):
S={}
for k,v in [Link]():
42
Accessing value of a global variable inside a function
G=10
def Test():
L=G+20 # Local Var
print("Main:",G)
43
Modifying global variable inside a function
"Int" IMMUTABLE type cannot be
G=100 modified inside function1
def Function1():
G+=20
44
Modifying global variable inside a function
"int" global keyword
G=100
required for immutable type
def Function1():
global G
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
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
47
Compare the codes
i=90 i=90
def test(j): def test():
j+=90 global 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
OUTPUT OUTPUT
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
● Can we access global object inside a function without using global keyword? YES
● 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
51
Happy Learning…
52