100%(1)100% found this document useful (1 vote) 135 views34 pagesWorking With Functions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
1 Python: Functions
2 | Types of Functions
3 1. Functions with no parameters and no return values.
4 2. Functions with parameters and no return value.
5 3. Functions with parameters and return value.
6 4. Functions with Multiple Return Values
7 Function Parameters and Arguments
8 Python: Types of Argument
9 1. Positional Arguments:
10 | 2. Default Arguments
11 | 3. Keyword Arguments
12 | 4, Variable length Positional Arguments
13 _| 5. Variable length Keyword Arguments
14 | Functions and Scopes 1. Global Scope: 2. Local scope: 3. Nonlocal variable
15 | Mutable/immutable Properties of Data Objects
16 _ | Passing String to Functions Passing Lists to Functions
17 _| Passing Tuples to Functions Passing Dictionaries to Functions
18 | Functions Using Mathematical Libraries:
19 | String methods & built in function:
Page of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
* A function is like a subprogram
A small program inside of a program
* The basic idea:
— We write a sequence of statements
— And give that sequence a name
— We can then execute this sequence at any time by referring to the
sequence’s name
* Functions reduce code duplication and make programs more easy to
understand and maintain
* Having identical (or similar) code in more than one place has various
downsides:
— Don’t want to write the same code twice (or more)
— The code must be maintained in multiple places
— Code is harder to understand with big blocks of repeated code
everywhere
* Functions are used when you have a block of code that you want to be able to:
— Write only once and be able to use again
* Example: getting input from the user
— Call multiple times at different places
Page 2 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
+ Example: printing out a menu of choices
— Differ a little bit when you call it each time
+ Example: printing out a greeting to different people
* Code sharing becomes possible
Keyword def 5 bas
Function Body
* Italways starts with the keyword def (for define)
«next after def goes the name of the function (the rules for naming functions
are exactly the same as for naming variables)
* after the function name, there's a place for a pair of parentheses (they
contain nothing here, but that will change soon)
«the line has to be ended with a colon;
* the line directly after def begins the function body - a couple (at least one) of
necessarily nested instructions, which will be executed every time the
function is invoked; note: the function ends where the nesting ends, so you
have to be careful.
* Function must be called/ invoked to execute.
Page 3 of 34Visit to websits
(Computation: mpythonacbse.com
Chapter-3: FUNCTIONS
‘We're ready to define our first program using function, =
The function is extremely simple, but fully usable. We've named it communication,
inking and Pros
let’s create it.
def communication ():
print ("Welcome to python programming’s World. ")
print ("We start here.")
print ("We end here.")
Note: we don't use the function at all in the above program - there's no invocation
or calling of it inside the code.
When you run the above code, you see the following output:
We start here.
We end here.
This means that Python reads the function's definitions and remembers them, but
won't launch any of them without your permission.
Now we've modified the above code
We've inserted the function's invocation between the start and end messages:
Invocation/Calling of functi
def communication( ):
World.")
peint("Welcome to python programming?
print ("We start here.")
--» communication() @-
print ("We end here.")
Page dof 34‘omputational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Uni
The output looks different now:
We start here.
Welcome to python programming’s World.
We end here.
It tries to show you the whole process:
© when you invoke a function, Python remembers the place where it happened
and jumps into the invoked function;
+ the body of the function is then executed;
‘* reaching the end of the function forces Python to return to the place directly
after the point of invocation
1. Functions with no parameters and noreturn values.
* Apython function without any arguments means you cannot pass data
* A function which does not return any value cannot be used in an
expression it can be used only as independent statement.
* Let's have an example to illustrate this.
function_prog.py - DyAmjad_CS/function_prog py (3.6.5) ull uur gett jee
File Edit Format Run Options Window Help
# 1. Functions with no arguments and no return values.
oan Semearten be inction without parameters
print ("Welcome to python programming’s World. "
print ("We start here.") =
communication ()
print ("We end here.")
No return keyword is used
ion body
Ld Cok
Page of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
OUTPUT:
We start here.
Welcome to python programming’s World.
We end here.
Before discussing second form of python’s function we must know,
* A parameter is a variable that is initialized when we call a function
+ parameters exist only inside functions in which they have been defined
* Parameters are given in the parenthesis ( ) separated by comma.
* Values are passed for the parameter at the time of function calling.
How Parameters Work?
* Each function is its own little subprogram
> Variables used inside of a function are local to that function
> Even if they have the same name as variables that appear outside that
function
* The only way for a function to see a variable from another function is for that
variable to be passed in as a parameter
We can create a communication () function that takes in a person's name (a string)
as a parameter
* This type of function can accept data from calling function
* We can control the output of function by providing various values as
arguments.
Page 6 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
* Let's have an example to get it better.
[reser Bite cencion peer 865) Zz
[Ftc tat Format Ran Options Window Help
#2. Functions with parameters and no return value.
seats [Parameter ‘name’ declared in function
def communication (name): 4
print ("Welcome to",name, "in python programming’s World. ") !
print ("We start here.")
‘communication ("Amit") |_ Calling of a function with argument ‘Amit’
print ("We end here.")
tnis Coro
OUTPUT:
We start here.
Welcome to Amit in python programming’s World.
We end here.
tees ead
Parameters are the name within Arguments are the values passed in
the function definition. when the function is called.
Parameters don’t change when the | Arguments are probably going to be
program is running different every time the function is
called.
This is also known as formal Arguments are also known as actual
parameters parameters.
——
oo [——— Function Parameter or Formal parameter
def communication (name)
print ("Welcome to",name, "in python programming’s World. "
Iprint ("We start here.")
Function Argument or Actual Parameter of
communication ("Amit") ———+ | 3 ginction
print ("we end here.
Page 7 of 34Unit i: Computational Thinking and Programming -2
‘Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
3. Functions with parameters and return value.
— To have a function return a value after itis called, we need to use the return
keyword
Handling Return Values
* When Python encounters return, it
> Exits the function
> Returns control back to where the function was called
> Similar to reaching the end of a function
The value provided in the return statement is sent back to the caller as an
expression result
The return value must be used at the calling place by -
> Either store it any variable
> Use with print()
> Use in any expression
* Let's have an example to illustrate this.
La function prog.py - DAmjad_CS/function prog py (3.65)
File Edit Format Run Options Window Help
#3. Functions with parameters and return value.
def Area (side):
R = side*side
return R
def main():
$ = float(input ("Enter the side of square:")
ar = Area(s)
print ("The area of square is: ",ar)
main()
Page of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Let’s follow the flow of the code:
Step 1: Call main()
Step 2: Pass control to def main()
Step 3: Enter the side of square of s (here, s=4)
Step 4: See the function call to Area ()
Step 5: Pass control from main () to Area ()
Step 6: Set the value of side in Area () tos
Step 7: Calculate side * side
Step 8: Return to main () and set ar = return statement
Step 9: Print value of ar
Sample Output:
Enter the side of square: 4
The area of square is: 16.0
Enter the side of square: 6
The area of square is: 36.0
* Sometimes a function needs to return more than one value
* Todo this, simply list more than one expression in the return statement
* In three ways we can do that:
— Using tuples
— Using list and
— Using dictionary
When calling a function with multiple returns, the code must also use multiple
assignments
Page 9 of 34‘Visit to website: learnpythondcbse.com
Unit i: Computational Thinking and Programming -2
Chapter-3: FUNCTIONS
* Assignment is based on position, just like passing in parameters is based on
nar, pr = Area(side, perimeter)
posi
* Let’s have an example to illustrate this.
|| inion pn Bei Rion Py OOF)
File Edit Format Run Options Window Help
#4. Functions with multiple return value.
Function has two parameters as
ram return the two values
def Area (side, perimeter) :
R = side*side
P = 2*perimeter
Keyword returns two values R and P
return (R,P) i i
to calling function
def main(
5 = float (input ("Enter the side of square for area:"))
Pp = float (input ("Enter the side of square for perimeter:"))
‘ar/pr = Area(s,p) Calling function Area with Actual parameters
Eee
print ("The area of square is: ",ar)
print ("The perimeter of square is: ",pr)
‘ar’ get the first value return i.e. a ‘pr’ get the second value return Le.
of square perimeter of square
OUTPUT:
Enter the side of square for area: 4
Enter the side of square for perimeter: 4
The area of square is: 16.0
The perimeter of square is: 8.0
Page 10 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
* Information can be passed into functions as arguments.
* Arguments are specified after the function name, inside the parentheses.
There are 5 types of Actual Arguments allowed in Python:
1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length Positional arguments
5. Variable length Keyword arguments
* positional argument is a name that is not followed by an equal sign (=) and
default value.
* When we pass the values during the function call, they are assigned to the
respective arguments according to their position.
For example, if a function is defined as
def demo(name, age):
and we are calling the function like :
demo("Ahil", "05")
then the value “Ahil” is assigned to the argument name and the value “05” is
assigned to the argument age.
Such arguments are called positional arguments.
Page 11 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Example:
1. the value 10 is as
to the argument
2. the value 5 is assign
to the argument y an
3. the value 15 is assigne
[a function prog py - D\Amjad, CS\hinction pog.py 253) El
File Ede Format Run Options Window Help
# Example: Positional Argument
def largest (x,y,z):
if x>y and x>z:
return x to the argument z.
elif y>x and y>z: 4. Such arguments are
veturn Y called positional
else:
return z arguments.
5. They match up, in that
order, to the
parameters the way
the function was
defined.
def main():
ee
L-largest (10, 5,15)
print ("Largest number is: ",L)
main()
Ln Coo
If we call it with a
ifferent number of
uments, the
ouTPUT:
D:\Amjad_cs\function_prog.py|
Largest number is: 15
1. Python allows function arguments to have default values.
2. If the function is called without the argument, the argument gets its default
value.
3. The default value is assigned by using assignment (=) operator of the
form keywordname=value.
Page 12 0f 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Example:
1 Parameter age is a
Fett Format fun Options Window Hep
+ Example: Default Argument
det info( name, age = 17 ):
"This prints a passed info into this function”
print ("Name: ", name)
print ("Age ", age)
return;
default argument.
2. If the function is
called without the
argument, the
argument gets its
default value.
. info (name =”Pooja”)
File Edit Shell Debug Options Window Help is called without age
D:\Amjad_cs\function_prog.py
value argument.
4. As we can seen in the
Name: Amit
Age 50
Name: Pooja }
Age 17
output the default
value is assigned i.e.
age 17
Ln:14 Cok 4 |
With Keyword arguments, we can use the name of the parameter irrespective
of its position.
* All the keyword arguments must match one of the arguments accepted by the
function.
* You can mix both positional and keyword arguments but keyword arguments
should follow positional arguments
Page 13 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
Example:
Point to Remember
Example: Keyword Argument | ‘
def infot nas. age)! 1. In case of passing
“this prints a passed info into this funcyiet” |] keyword argument,
print ("Name: “, name) order of arguments
Cage" oreere
prank fase is not important.
2. There should be
fatot Sgen20, nanewranit Mean, eal ereatetad
info( "Pooja",age=17 ) one parameter.
info( age=17 )w. 13. The passed
keyword name
should match with
the actual keyword
name
cs\ function prog.py = 14. In case of calling
= . function containing
Name: non-keyword
age 20 arguments, order is
Name: Pooja important.
age 17
Traceback (most recent call last) : /]5: we call it with a
different number of
, line i in arguments, the
info( age=17 ) ‘ interpreter will
TypeError: info() missing 1 required show an error
positional argument: 'name' message.
* It is useful when we are not certain about number of arguments that are
required in the function definition or function would receive.
* Iti quite useful to write functions that take countless number of positional
arguments for certain use cases.
Page 14 0f 34* Python function first fills the slots given formal argument:
positional actual arguments.
which is available through variable which is having prefixe
definition.
Example:
Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
s by passed
* Any leftover actual (positional) arguments are captured by python as a tuple,
d * in the function
La enon ogy Orel Cer 7 (6
Fafa Fert Ran Opts Window Hep
# Example: Variable lenght Argument
‘es varingt( argl,arg2, ‘vartupl )
1.
print ("Regular Positional Arguments: " ,argl,arg2)
print ("Variable Length arguments", vartupl)
# Now you can call varlngh function
varlngt ( 10 ,20)s00,
print ()
varlngt ( 30, 40) 50, 60,70),
File Edit Shell Debug Options Window Help
RESTART: D:\Amja:
cS\function_prog.py ================
fReguiar Positional Arguments: 10 20
[variable Length arguments ()
fav
variable Length arguments (50, 60, 70
nil Cob:
Regular Positional Arguments: 30 40 J
ye
laa
Page 15 of 34
Point to Remember
Variables argi, arg2
need to be filled by
actual arguments
any leftover passed
arguments can be
accessed as tuple
using vartupl.
.. Since there are no
extra positional
arguments are
passed in the above
function call. The
variable vartupl is a
empty tuple.
. As you can see in the
function call, left
over arguments are
added to tuple and
can be accessed
using given variable
vartupl.‘Visit to website: learnpythondcbse.com
Unit i: Computational Thinking and Programming -2
Chapter-3: FUNCTIONS
‘5. Variable length Keyword Arguments
* Variable length keyword arguments are very much similar to variable length
positional arguments.
* Itis the mechanism to accept variable length arguments in the form keyword
arguments
* It is useful if we are not certain about number of keyword arguments that,
function receives.
* Python functions captures all extra keyword arguments as dictionary and
* Makes it available by name (variable) which is prefixed by ** in the function
definition.
Example:
La uncon progpy - DVanjad_ Venton prog py (8.55)
Fle E&t Format Rin Options Window Help
Point to Remember
# Example: Variable lenght keyword Argument,
det varlngtkat argi,arg2, **kvarg 0 2. Variables arga, arg2
need to be filled by
print ("Regular Positional argunents: " ,argi,arg2) | actual arguments any
leftover passed
arguments can be
accessed as,
dictionary using
kwarg.
2. Since there are no
extra positional
arguments are
passed in the above
function call. The
variable kwarg is a
empty dictionary.
‘As you can see in the
function call, left
‘over arguments are
added to dictionary
and can be accessed
using given variable
kwarg.
print ("variable Length arguments", kwarg)
# Now you can call varlngh function
varlngtkd( arg2=10 ,argi=20 )*
print()
varlngtkd( 30, arg2=40, a=50,b=60,c=70 Je,
OUTPUT:
PY .
festiar Positional arguments: 20 10]
friable Length arguments ()
Regular Positional Arguments: 30 40 Wj
ariable Length arguments {"a': 50, 'b': 60, 'c': 70)
ett Cote
Page 16 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
* Ascope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable can’t be accessed
* Scope determines visibility of identifiers across function/procedure boundaries
In Python 3.x there are broadly 3 kinds of Scopes:
1. Global Variable
2. Local Variable
3. Nonlocal Variable
* Avariable, with global scope can be used anywhere in the program.
* Itcan be created by defining a variable outside the scope of any function/block.
* Itcan be accessed inside or outside of the function.
Let's see an Example 1 of how a global variable is create:
Pecorino ea)
Example 1: Z ;
Fie Edt_Forat_Run_Optors_Window Hep
# 1.Create a Global Variable
OUTPUT: gib = “global
def fun():
glb in fun : global print ("glib in fun
2", glb)
glb out of fun : global
fun()
print("glb out of fun:", glb)
ea Cobar
— The variable gbl is defined
as global variable in above code.
— The only statement in fun() is the “print” statement.
— As there is no local glb, the value from the global glb will be used.
Page 17 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
© Changing the value of global variable ‘glb’ inside a function will not affect its
global value
Example 2: OUTPUT
Treat as local variable inside
the fun()
glb inside fun : New glb
[tion prog py bana. funion 9659 059)
# 2.Create a Global Variable
glb = "global"
glb outof fun : global
def fun(Q):
glb="New glb"
print("glb inside fun
fun()
No change in global variable
gib
* If you need to access and change the value of the global variable from within a
function, this permission is granted by the global keyword.
Example 3: The below given code is same as the example 2 except the use of global
keyword.
Es
2 function prog py - DYAmjad,CSunction prog-py 3.65)
Fle Edt Format Run Options Window Help
# 3.Create a Global Variable
OUTPUT:
glb = "global"
glb inside fun : New glb
def fund:
global glb
glb="New glb"
glb outof fun : New glb
print ("glb inside fun :", glb)
fun()
print ("glb outof fu
Page 18 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Working of above code:
* Inthe above program, we define glb as a global keyword inside the fun ()
function.
* Then, we assign new string to the variable glb i.e. glb = “New glb”.
* After that, we call the fun() function.
* Finally, we print the global variable glb.
* As we can see, change also occurred on the global variable outside the
function, glb= “New glb”.
* Avariable with local scope can be accessed only within the function/block
that it is created in.
© When a variable is created inside the function/block, the variable becomes
local to it.
A local variable only exists while the function is executing.
def funQ:
ible only
function fun ()
1cl="Local"
print("lcl inside fun :", 1cl)
fun()
print("lcl access outside of fun:", 1cl)|-
1cl inside fun : Local
Traceback (most recent call last):
File "D:/Amjad_cS/function_prog.py"
, line 8, in
print ("lcl access outside of fun:
1cl)
NameError:
Icl can’t be ac
outside the fun( ) i.e.
not visible or can’t
be used outside the
name 'lcl' is not defined
Page 19 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
* Nonlocal variables are used in nested functions whose local scope is not
defined.
© The outer function’s variables will not be accessible in inner function if we do
the same, a variable will be created as local in inner function.
* Insuch a case, we can define the variable (which is declared in outer function)
as a nonlocal variable in inner function using nonlocal keyword.
* Let's see an example of how a keyword nonlocal is used:
# An example of use of Non Local variable
# D:\amjad_cs\function_prog.py
# Nested Functions
def ofun():
x=5
y= 10
def infun():
# nonlocal binding
nonlocal x
x = x+50 # x will update
y= 100 # y will not update,
# it will be considered as a local variable
# and not accessible outside infun()
# calling inner function
infun() OUTPUT:
# printing the value of a and b
print ("The value of x is: ", x) The value of x is: 55
print ("The value of y is: ", y)
10
The value of y i:
# calling the function i.e. ofunc()
ofun()
Explanation of above code:
* As you see in the output, x and y are the variables of ofun() and
* inthe infun() we declared variable x as nonlocal, thus x will not be local here
but y will be considered as local variable for infun() and
Page 20 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
* if we change the value of y that will be considered a new assigned for local
variable(for infun()) y,
* If we change the value of a nonlocal variable x (here, x= 50+x), the changes
appear in the local variable of outer function (for ofun()) also.
Mutable/Immutable Properties of Data Objects
Func (Formal_B):<—
Statements function Fune (is called
Statements 7
Func (Actual_A)
ee enc)
ee RC)
IF Actual_Ais
immutable
(int, float, string, tuple)
Actual_A Formal Bis assigned [J Formal_Bis modified
doesn't change to something else in place
If Formal_B changes LB=[0, Formal_8.append (9)
changes
Common immutable type
1. Numbers: int, float, complex
2. Immutable Sequences: string, tuple
This means the value of integer, float, string, complex or tuple is not changed in the
calling block if their value is changed inside the function.
Page 21 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Common mutable type (almost everything else):
1. Mutable sequences: list
2. Set type: set
3. Mapping type: dict
Example:
(S function prog.py - D’VAmjad_CS\function =e) aie)
File Edit Format Run Options Window Help
# Immutable objects in python +]
def tuple_Immut (num) :
num += (4,5,)
return num
Tuple x is passed to function
tuple_Immut() and function
updates the tuple
x= (1, 2, 3)
y = tuple_immut (xJ
RESTART: D:\ *
Amjad_Cs\functio
print (y)-
print (x)
# Mutable objects in python L
def list_Mutable (num):
num += [4,5]
return num
x= (1, 2, 3]
y = list_Mutable (x
List xis passed to function
list_Mutable()function
updates the list
print (y) —
print (x)=
* We see in output that the tuple x can’t change when we pass it to tuple_Immut()
function. This is because tuple is an immutable object, so | cannot change it.
* But list x changes when we pass it to list_Mutable() function. This is because lists
are mutable.
Page 22 0f 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
* Function can accept string as a parameter
* If you pass immutable arguments like strings to a function, the passing acts like
call-by-value so function can access the value of string but cannot alter the
string
* To modify string, the trick is to take another string and concatenate the
modified value of parameter string in the newly created string.
* Let us see few examples of passing string to function.
Example 1: Write function that will accept a string and return reverse of the
string.
# function definition: it will accept
# a string parameter and return reverse of string
def str_rev(str):
revstr = ''
index = len(str)
while index > 0:
revstr str[ index - 1 ]
index = index - 1
return revstr
s='abcde12345'
print ("The reverse of ",s,'is',str_rev(s))
function_prog.py = ~ F|
The reverse of abcde12345 is 54321edcba_
nm? Coka
Page 23 of 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUN Co}. E)
Example 2: Write a Python function that accepts a string and calculate the number
of upper case letters and lower case letters.
Le function prog.py - D:\Amjad_CS\function._prog.py (36.5)
Eat_Format Run Options Window Help
# function definition: it will accept
# a string parameter and return number of
# upper case letters and lower case letters
def str_COUNT(s):
uc=t
Lk
c in s:
if c.isupper():
UC+
elif c.islower():
Lc+
else:
pass
print ("Original string : ", s)
print ("No. of Upper case characters : ", UC)
print ("No. of Lower case Characters : ", LC)
str_COUNT('Learn Python With Fun')
Ln20 Cok3
File Edit Shell Debug Options Window Help
RESTART: D:\Amjad_Cs\
function_prog.py ============
Original String : Learn Python With Fun
No. of Upper case characters : 4
of Lower case Characters : 14
Page 24 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
* We can also pass List to any function as parameter
* Due to the mutable nature of List, function can alter the list of values in place.
+ Itis mostly used in data structure like sorting, stack, queue etc.
Example 1: Write a Python function that takes a list and returns a new list with
unique elements of the first list.
Lg function_prog.py- mje CStncton progpy 365) Eas
File Edit Format Run Options Window Help —
# takes a list and returns a new list
# with uniqueelements of the first list.
def unique 1st (1st):
L=
for i in lst:
if i not in L:
L. append (i)
return L
print (unique_1st ({1,2,3,3,3,3,4,5]))
File Edit Shell Debug Options Window Help
D:\Amjad_Cs\function_prog.py
(1, 2, 3, 4, 5]
\|>>>
Page 25 of 34Unit i: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Example 2: Write a Python function to multiply all the numbers in a list.
(function progpy - DVAmjed CSiincton pregy 355) =
File fait Format Run Options Window Help
|# Write a python function to multiply +
# all the numbers in a list. al
def mult_1st (num):
total = 1
for ¢ in num
total *=c
return total
Ist=[3,5,7,3,-1]
print (mult_1st (1st))
Lied Cok?
L.@ Python 3.6.5 Shell —
File Edit Shell Debug Options Window Help
D:\Amjad_cs\function_prog.py
© Function can accept tuples as a parameter
* If you pass immutable arguments like tuple to a function, the passing acts like
call-by-value so function can access the value of tuple but cannot alter the
tuple.
* Let us see an example of passing tuples to function.
Page 26 0f 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
Example 1: Print the prime numbers from give list of numbers using tuple passing to
function.
1. Iterate through each number in a list
2. Check whether it is divisible by 2 or more numbers
3. If num is divisible by itself and 1 then it is prime and stores it in tuple.
# function definition: it will accept
# a list of numbers as parameter and return list
# of prime number from the give list
def countPrime (mytup) :
prime=()
for i in mytup:
c=0
for jin range(1,i):
if ity
cel
This statement used to
_ concatenate tuple item i
to tuple prime
if
prime = prime + (i,)
return prime
mytuple =(
n=int (input("Enter how many number :"))
for i in range (n)+
number=int (input ("Enter any numbber.."))
nytuple-mytuple + (number, )
primetuple=count Prime (mytuple)
print ("List of prime numbers:",primetuple)
tem Coto
RESTART: D:\Amjad_Cs
\function_prog.py
Enter how many number :5
Enter any numbber..2
Enter any numbber..5
Enter any numbber..7
Enter any numbber..10
Enter any numbber..11
List of prime number:
(2, 5, 7, 11)
Page 27 of 34‘Visit to website: learnpythondcbse.com
Unit i: Computational Thinking and Programming -2
Chapter-3: FUNCTIONS
* Python also allows us to pass dictionaries to function
* Due to its mutability nature, function can alter the keys or values of dictionary
in place
Example:
# passing dictionary to function
Ce! my function (school, standard, city, name):
schoolNane = school
citywane = city
standardNane = standard
studentNane = name
print ("student Nane: ";name)
Print ("school Nano: *, SchoolNane)
print ("city Name: ",cltysane)
print ("clase ",standardNane)
detail = {'school':'KPS', ‘standard': "12", ‘name’
my_function(**detail)
print (" oR
tamit', ‘city': "Delni")
)
PU EUENETE OR TETENET EET ESET
cet my_function(**data) :
schoolname = data{'school']
cityname = data('city")
standard = data['standard"]
studentname = data['name']
print ("student Name: ", studentname)
print ("school Name: ", schoolname)
print ("city Name: ",cityname)
print ("Class: ", standard)
detail = {'school':'KPS', ‘standard': ‘11, ‘name': ‘amaan', ‘city't 'Delhi')
my_function (**detail ; .
vA ‘ > ART: D:\amjad_cs\functio
n_prog-py =
OUTPUT:
Student Name: Amit
School Name: KPS
City Name: Delhi
student Name: aAmaan
School Name: KPS
City Name: Delhi
Class: 11.Unit: Computational Thinking and Programming -2 Visit to website leampythondcbe.com
Chapter-3: FUN Co}. E)
irene Derr cal peered ‘Output
prototype
math.ceil(x) It returns the smallest >>>math.ceil(-45.17) 45
Integernotlessthan¥, 5>smathceil(100.12) 101
where x is a numeric
ee >>>math.ceil(100.72) 101
math.sart(x) Itreturns the square root >>>mathsqrt(100) 10
of x forx>0, Se xisa >>>math.sqrt(7) 2.645751311
numeric expression.
math.exp(x) It returns exponential of | >>>math.exp(-45.17) 2.42E-20
X@p,wherexisa —-SsSiathexp(10012) | 03E43
numeric expression.
>>>mathexp(100.72) 5.52E+43
math. fabs(x) Itreturns the absolute >>>mathfabs(-45.17) 45.17
value of wherex isa >oyathfabs(100.12) 100.12
‘numeric value.
>>>mathfabs(100.72) 100.72
math floor(x) Itreturns the largest >>>mathloor(-45.17) 46
integer not greater than | ssathisloor(100s12)) 100)
x, where x is @ numeric
expression. >>>mathfloor(100.72) 100
math.log(xbase) It returns natural logarithm >>>math.log(100.12) 4.606368467
of x, forx>0, where xis@
Tumeviccrprossion >>>tatlog(100.72) — 4,61234439
math loglO(x) Itreturns base-10 | SSSimtathuloglO(i00Li2y"))2.000520844
logarithm of x for x>0,
where x is a numeric >>>mathlogl0(100.72) 2.003115717
expression,
math.pow(base,e Itreturns the value of — >>>math.pow(100, 2) 10000
xp) base and exp, where > >math.pow(100,-2) 0.0001
base and exp are Ske
numeric expressions. | >>>math.pow/(2, 4) 16
>>>math.pow(3,0) 1
Page 200634Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUN ONS
math.sin(arg) Itreturns the sine of arg, >>>math.sin(3) 0.141120008
inradians, where arg >> math sin(-3) -0.141120008
must be a numeric value.
>p>imathsin(0) 0
math.cos(arg) It returns the cosine of x >>>math.cos(3) -0.989992497
in >>>math.cos(3) -0.989992497
>>>math.cos(0) 1
>>pmath.cos(mathpi) 1
math.tan(arg) Itreturns the tangent of | >>>math.tan(3) -0.142546543
xin radians, where org ssssisathitan(3) 0.142546843
must be a numeric value.
>>>math.tan(0) °
math.degree(x) It converts angle x from >>>math.degrees(3) 171.8873385
radians to degrees, math degrees(-3)_-171.8873385
where x must be a
numeric value. peemath.degrees(0) 0
math.radians(x) _Itconverts angle x from >>>math.xadians(3) __0.052359878
degrees toradians, 5 sSsathwadians(3) | -0.052359878
where x must be a
numeric value. >>>mathzadians(Q) 0
abs (x) Itreturns distance >>>abs(-45) 45
between x and zero,
where x is a numeric
expression.
Itreturns the largest of | >>>max(80, 100, 1000) 1000
its arguments: where x, y
and z are numeric
variable/ expression.
Itreturns the smallest of | >>> min(80, 100, 1000) 80
its arguments; where x,
y, and 2 are numeric
variable/expression.
>>>abs(119L) 119
max( x, y, 2,
>>>max(-80,-20,-10) 10
MIN X,Y, 2 oe
>>> min(-80,-20,-10) 80
empl x,y) It returns the sign of the _>>>emp(80, 100) Ey
ALifxsy,Oifx==y,0r1 > cmpc1so, 100) 7
divmod (x,y ) Returns both quotient >>> divmod (14,5) (24)
Page 30 of 34Unit i: Computational Thinking and Programming -2
‘Visit to website: learnpythondcbse.com
Coy Ey scree ee ONS
and remainderby |) >>> divmod (27,15) (1.0, 1.20000)
division through a tuple,
when xis divided by y;
where x & y are variable
/expression.
len (s) Return the length (the >>> a= [123]
number of items) fan ton (ay 3
‘object. The argument
maybeasequence >>> b= “Hello”
(string, tupleor list) ora >>> Jen (b) 5
mapping (dictionary).
round( x n}) Itreturns floatx _ >>>round(80.23456,2) 80.23
rounded.
>>>round(-100.000056, 100
Ifnis not providedthen 3)
xis rounded to 0 decimal 55 sound (80.23156) 80
digits.
Lets Consider two Strings: str1="Save Earth" and str2='welcome’
Aili Description eed
Ten() Return the length of the [>>> pant (Len(strl))
string 10
capitalize () | Return the exact copy of | "> >prant (str2.capitalize())
the string with thefirst_ | Welcome
letter in upper case
isalnump) Returns True the SSoprint (str. isalnum())
string contains only rALSE
letters and digit. It
eum fase the |The function returns False as space
“ ’ is an alphanumeric character.
string contains an
special character tke _, | 22 PEint ('SavelEarth' . isalnum())
@i,* etc. TRUE
isalpha) Returns True the 35> print (‘Clicki23’ .isalpha())
string contains only
letters. Otherwise
return False.
FALSE
>>> print ("python' .isalpha())
TRUE
Page 31 of 34Unit i: Computational Thinking and Programming -2
Chapter-3: FUNCTIONS
‘Visit to website: learnpythondcbse.com
isdigit() Returns True if the >>>print (str2.isdigit 0)
string contains only FALSE
numbers. Otherwise it
returns False.
Tower() Returns the exact copy _|>>>prant (stri.lower())
of the string with all the | save earth
letters in lowercase.
islower{) Returns True if the SSoprint (str2.islower())
string is in lowercase. ‘TRUE
isupper() Returns True if the Soopeint (ste2.isupper 0)
string is in uppercase FALSE
upper() Returns the exact copy |>>>print (str2.upper())
of the string with all
letters in uppercase. WELCOME
find(sub[start[ | The function is usedto | >>>ste-"mammals'
vend]}) | search the first >>>str.find('ma')
occurrence of the °
substring in the given
string, It returns the
index at which the On omitting the start parameters,
substring starts. It the function starts the search
returns -1 if the fromthe beginning.
substring does occurin Joos ind (ema’,2)
the string. 3
>oostr. find ('ma',2, 4)
-1
Displays -1 because the substring
could not be found between the
index 2 and 4-1
>>>str. find ('ma',2,5)
3
Istrip() Returns the string after >>> print (str)
removing the space(s)
on the right of the
string.
Save Earth
ooostr-Istrip()
‘Save Earth’
>>>str='Teach India Movement!
Page 32 0f 34Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com
Chapter-3: FUNCTIONS
>o> print (str.1strip("T"))
each India Movement
>>> print (str.1strip("
ach India Movement
e"))
>>> print str.1strip("Pt")
Teach India Movement
If a string is passed as argument
to the Istrip() function, it
removes those characters from the
left of the string.
rstrip() Returns the stringafter_ | >>>st.
removing the space(s)
Teach India Movement"
>>> print (str.rstrip())
on the right of the Teach India Movement
string.
isspace() | Returns True if the SS stra
string contains only | >>> print (str.isspace())
white spaces and False | pays
even if it contains one
>>> str='p!
character. :
>>> str.isspace())
FALSE
istitiet) Returns True ifthe 35> str="The Green Revolution’
strings title cased. oo> str.istitle()
TRUE
>>> str='The green revolution’
>o> str-istitle()
FALSE
replace(old, | The function replaces all | >>>st=="hel Io"
new) the occurrences ofthe | >>> print (str.replace('l','8"))
old string with thenew | nesso
string ‘
>o> print (str.replace('1','88'))
hevesto
join() Returns a string in >>> stri=("jan', ‘feb ,‘mar')
which the string. po>str="e”
elementshavebeen [535 sex.join(strl)
joined bya separator. | ys eansmar’
Page 33 of 34Unit i: Computational Thinking and Programming -2
Chapter-3: FUNCTIONS
‘Visit to website: learnpythondcbse.com
swapcase() | Returns the string >>>_str='UPPER™
case changes 35> print (str. swapcase ())
upper
>>> str" lower
>>> print (str.swapcase())
LOWER
partition(sep) | The function partitions | >>> stz="The Green Revolution’
the strings at the first
occurrence of
separator, and returns
the strings partition in
three parts i.e. before
the separator, the
separator itself, and the
part after the separator.
If the separator is not
found, returns the string
itself, followed by two
empty strings.
>o> str.partition('Rev')
(The Green ', 'Rev', 'olution')
>>> str-partition('pe')
(The Green Revolution",
>>> str.partition('e')
Cth’, Green Revolution’)
tet
split({sep[,max
split]))
The function splits the
string into substrings
using the separator. The
second argument is,
optional and its default
value is zero. If an
integer value N is given
for the second
argument, the string is
split in N#1 strings.
>>>ste= ThegearthSis§whatgwesall
$have$in$common.'
>o> str.split ($,3)
SyntaxError: invalid syntax
>>> str.split('$",3)
['The', ‘earth',
‘is’, 'what§we§all$have$in$common. ']
>>> str.split ('$")
['The', ‘earth’,
fall',‘have', |
‘is’, ‘what’,
>o> ste.split('e')
Uh, ' Get, '', 'n R!, 'volution']
>o> str.split('e',2)
UTh', ' Gxt, ‘en Revolution']
Page 34 of 34