Functions
Functions
com
Chapter-3: FUNCTIONS
In this tutorial we will discuss the following topics
S. No. Topics
1 Python: Functions
2 Types of Functions
9 1. Positional Arguments:
10 2. Default Arguments
11 3. Keyword Arguments
Page 1 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Python: Functions
Having identical (or similar) code in more than one place has various
downsides:
Functions are used when you have a block of code that you want to be able to:
Chapter-3: FUNCTIONS
• Example: printing out a menu of choices
Point to Remember:
It always 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 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.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,
let’s create it.
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.
Page 4 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
The output looks different now:
We start here.
Welcome to python programming’s World.
We end here.
Page 5 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
OUTPUT:
We start here.
Welcome to python programming’s World.
We end here.
What is a Parameter?
A parameter is a variable that is initialized when we call a function
parameters exist only inside functions in which they have been defined
Values are passed for the parameter at the time of function calling.
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
Chapter-3: FUNCTIONS
Let’s have an example to get it better.
Page 7 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
3. Functions with parameters and return value.
– To have a function return a value after it is 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.
Page 8 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.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 () to s
Step 7: Calculate side * side
Step 8: Return to main () and set ar = return statement
Step 9: Print value of ar
Sample Output:
Chapter-3: FUNCTIONS
Assignment is based on position, just like passing in parameters is based on
position : ar, pr = Area(side, perimeter)
Let’s have an example to illustrate this.
‘ar’ get the first value return i.e. area ‘pr’ get the second value return i.e.
of square perimeter of square
OUTPUT:
Page 10 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Python: Types of Argument
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
1. Positional Arguments:
A 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.
demo("Ahil", "05")
then the value “Ahil” is assigned to the argument name and the value “05” is
assigned to the argument age.
Page 11 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Example:
2. Default Arguments
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 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Example:
1. Parameter age is a
default argument.
2. If the function is
called without the
argument, the
argument gets its
default value.
3. info (name =”Pooja”)
is called without age
value argument.
4. As we can seen in the
output the default
value is assigned i.e.
age 17
3. Keyword Arguments
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 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Example:
Point to Remember
1. In case of passing
keyword argument,
order of arguments
is not important.
2. There should be
only one value for
one parameter.
3. The passed
keyword name
should match with
the actual keyword
name.
4. In case of calling
function containing
non-keyword
arguments, order is
important.
5. If we call it with a
different number of
arguments, the
interpreter will
show an error
message.
Chapter-3: FUNCTIONS
Python function first fills the slots given formal arguments by passed
positional actual arguments.
Any leftover actual (positional) arguments are captured by python as a tuple,
which is available through variable which is having prefixed * in the function
definition.
Example:
Point to Remember
Page 15 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
5. Variable length Keyword Arguments
Variable length keyword arguments are very much similar to variable length
positional arguments.
It is 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:
Point to Remember
Chapter-3: FUNCTIONS
Functions and Scopes
A scope 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
Global and local Variables in Functions
In Python 3.x there are broadly 3 kinds of Scopes:
1. Global Variable
2. Local Variable
3. Nonlocal Variable
1. Global Scope:
A variable, with global scope can be used anywhere in the program.
It can be created by defining a variable outside the scope of any function/block.
It can be accessed inside or outside of the function.
Let's see an Example 1 of how a global variable is create:
Example 1:
OUTPUT:
glb in fun : global
Page 17 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Changing the value of global variable ‘glb’ inside a function will not affect its
global value.
Example 2: OUTPUT
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.
OUTPUT:
Page 18 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Working of above code:
In the 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”.
2. Local scope:-
A variable 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.
Page 19 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
3. Nonlocal variable
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.
In such 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:
OUTPUT:
Page 20 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.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.
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 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Common mutable type (almost everything else):
Example:
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 I cannot change it.
But list x changes when we pass it to list_Mutable() function. This is because lists
are mutable.
Page 22 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Passing String to Functions
Example 1: Write function that will accept a string and return reverse of the
string.
Page 23 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Example 2: Write a Python function that accepts a string and calculate the number
of upper case letters and lower case letters.
Page 24 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Passing Lists to Functions
Example 1: Write a Python function that takes a list and returns a new list with
unique elements of the first list.
Page 25 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Example 2: Write a Python function to multiply all the numbers in a list.
Page 26 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Example 1: Print the prime numbers from give list of numbers using tuple passing to
function.
Page 27 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Passing Dictionaries to Functions
Example:
OUTPUT:
Page 28 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
Functions Using Libraries: Mathematical
and String Functions
Functions Using Mathematical Libraries:
S.No. Function and its Description Example Output
prototype
1 math.ceil(x) It returns the smallest >>>math.ceil(-45.17) -45
integer not less than x, >>>math.ceil(100.12) 101
where x is a numeric
expression. >>>math.ceil(100.72) 101
Page 29 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
9 math.sin(arg) It returns the sine of arg, >>>math.sin(3) 0.141120008
in radians, where arg >>>math.sin(-3) -0.141120008
must be a numeric value.
>>>math.sin(0) 0
Page 30 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
and remainder by >>> divmod (2.7, 1.5) (1.0, 1.20000)
division through a tuple,
when x is divided by y;
where x & y are variable
/expression.
19 len (s) Return the length (the >>> a= [1,2,3]
number of items) of an >>>len (a) 3
object. The argument
may be a sequence >>> b= “Hello”
(string, tupleor list) or a >>> len (b) 5
mapping (dictionary).
20 round( x [, n] ) It returns float x >>>round(80.23456, 2) 80.23
rounded. >>>round(-100.000056, -100
If n is not provided then 3)
x is rounded to 0 decimal >>> round (80.23456) 80
digits.
Page 31 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
isdigit() Returns True if the >>>print (str2.isdigit())
string contains only FALSE
numbers. Otherwise it
returns False.
lower() Returns the exact copy >>>print (str1.lower())
of the string with all the save earth
letters in lowercase.
islower() Returns True if the >>>print (str2.islower())
string is in lowercase. TRUE
isupper() Returns True if the >>>print (str2.isupper())
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 used to >>>str='mammals'
, end]]) search the first >>>str.find('ma')
occurrence of the 0
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 occur in >>>str.find('ma',2)
the string. 3
>>>str.find('ma',2,4)
-1
Chapter-3: FUNCTIONS
>>> print (str.lstrip("T"))
each India Movement
>>> print (str.lstrip("Te"))
ach India Movement
>>> print str.lstrip("Pt")
Teach India Movement
If a string is passed as argument
to the lstrip() function, it
removes those characters from the
left of the string.
rstrip() Returns the string after >>>str='Teach India Movement'
removing the space(s) >>> print (str.rstrip())
on the right of the Teach India Movement
string.
isspace() Returns True if the >>> str=' '
string contains only >>> print (str.isspace())
white spaces and False TRUE
even if it contains one
>>> str='p'
character.
>>> str.isspace())
FALSE
istitle() Returns True if the >>> str='The Green Revolution'
string is title cased. >>> str.istitle()
TRUE
>>> str='The green revolution'
>>> str.istitle()
FALSE
replace(old, The function replaces all >>>str=‟hello‟
new) the occurrences of the >>> print (str.replace('l','%'))
old string with the new He%%o
string
>>> print (str.replace('l','%%'))
he%%%%o
Page 33 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com
Chapter-3: FUNCTIONS
swapcase() Returns the string with >>> str='UPPER'
case changes >>> print (str.swapcase())
upper
>>> str='lower'
>>> print (str.swapcase())
LOWER
partition(sep) The function partitions >>> str='The Green Revolution'
the strings at the first >>> str.partition('Rev')
occurrence of ('The Green ', 'Rev', 'olution')
separator, and returns
>>> str.partition('pe')
the strings partition in
three parts i.e. before ('The Green Revolution', '', '')
the separator, the >>> str.partition('e')
separator itself, and the ('Th', 'e', ' Green Revolution')
part after the separator.
If the separator is not
found, returns the string
itself, followed by two
empty strings.
split([sep[,max The function splits the >>>str='The$earth$is$what$we$all
split]]) string into substrings $have$in$common.'
using the separator. The >>> str.split($,3)
second argument is SyntaxError: invalid syntax
optional and its default
>>> str.split('$',3)
value is zero. If an
integer value N is given ['The', 'earth',
for the second 'is','what$we$all$have$in$common.']
argument, the string is >>> str.split('$')
split in N+1 strings. ['The', 'earth', 'is', 'what', 'we',
'all','have', 'in', 'common.']
>>> str.split('e')
['Th', ' Gr', '', 'n R', 'volution']
>>> str.split('e',2)
['Th', ' Gr', 'en Revolution']
Page 34 of 34