Functions
Functions
Computer Science
Class XII ( As per
CBSE Board)
Functions
def my_own_function():
#Function block/
print("Hello from a function") definition/creation
a, b, x, y = 1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun()
print(a, b, x, y)
a, b, x, y = 1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun()
print(a, b, x, y)
OUTPUT :-
10 30 100 50
10 2 3 4
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 100
x in main: 200
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
Visit : python.mykvs.in for regular updates
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):
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
#default value of x and y is being used #now the above function sum() can sum
when it is not passed n number of values
E.g.
x = lambda a, b : a * b
print(x(5, 6))
OUTPUT:
30
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
Visit : python.mykvs.in for regular updates
Functions using libraries
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
String functions:
String functions are available in python standard module.These are always
availble to use.
For e.g. capitalize() function Converts the first character of string to upper
case.
OUTPUT:
I love programming
String functions:
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
String functions:
Method Description
Returns a string where a specified value is replaced with a
replace()
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
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning