Functions in Python
References
• Taming Python by Programming, Dr Jeeva Jose Rincy T A
• Introduction to computing and problem solving using
python by Balaguruswamy Asst Professor in Computer Science
Prajyoti Niketan College, Pudukad
2
▪ A function is a block of organized, reusable
code that is used to perform a single, related
action.
▪ Functions provide better modularity for your
application and a high degree of code reusing.
Functions ▪ Python gives you many built-in functions like
print(), etc. but you can also create your own
functions.
▪ These functions are called user-defined
functions.
Functions in Python
3
▪ Function blocks begin with the keyword def followed by the
function name and parentheses ( ( ) ).
▪ Any input parameters or arguments should be placed within
these parentheses. You can also define parameters inside these
parentheses.
▪ The first statement of a function can be an optional statement -
Defining a the documentation string of the function or docstring.
Function ▪ The code block within every function starts with a colon (:) and
is indented.
▪ The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with
no arguments is the same as return None.
Functions in Python
4
def functionname( parameters ):
"function_docstring"
function_suite
Syntax & return [expression]
▪ By default, parameters have a positional behavior and you need
Example to inform them in the same order that they were defined.
def printme( str ):
"This prints a passed string into this function"
print str
return
Functions in Python
5
▪ Defining a function only gives it a name, specifies the
parameters that are to be included in the function and structures
Calling a the blocks of code.
Function ▪ Once the basic structure of a function is finalized, you can
execute it by calling it from another function or directly from
the Python prompt.
Functions in Python
6
Pass by ▪ All parameters (arguments) in the Python language are passed
reference vs by reference.
▪ It means if you change what a parameter refers to within a
value function, the change also reflects back in the calling function.
Functions in Python
7
def cal(a,b):
print(a+b)
return
Example #main pgm
a=int(input("enter first num"))
b=int(input("enter sec num"))
cal(a,b)
======================== RESTART: F:\Python ex\
fn1.py ========================
enter first num10
enter sec num20
30 Functions in Python
>>>
8
def cal(a,b):
return(a+b)
Example 2 #main pgm
a=int(input("enter first num"))
b=int(input("enter sec num"))
print("sum is ",cal(a,b))
======================== RESTART: F:\Python ex\
fn1.py ========================
enter first num10
enter sec num20
sum is 30 Functions in Python
>>>
9
>>>def print_lines():
print(“Hello Python”)
print(“Welcome to Python Programming”)
Examples
>>>print_lines()
Hello Python
Welcome to Python Programming
Functions in Python
10
▪ The rules for defining a function name are same as those for variable
names: alphabets, numerals and some special characters are allowed.
▪ The name of a function cannot start with a number.
▪ No keyword can be used as the name of a function.
More to ▪ Giving the same name to a variable and a function should be avoided.
▪ The parenthesis after the function name contain the parameters or
read... arguments. They are optional.
▪ The first line in the definition of a function is known as header and the
rest is abbreviated as the body.
▪ The header line will always end with a colon.
Functions in Python
11
>>>def print_lines():
print(“Hello Python”)
print(“Welcome to Python Programming”)
>>>def new_print():
A function print_lines()
calling print_lines()
another
function >>new_print()
Hello Python
Welcome to Python Programming
Hello Python
Welcome to Python Programming
Functions in Python
12
▪ Parameters and arguments are the values or expressions passed
to the functions between parenthesis.
▪ Many of the built-in functions need arguments to be passed
Function with them.
Parameters ▪ The value of the argument is always assigned to a variable
and known as parameter.
Arguments ▪ At the time of the function definition, we have to define some
parameters if that function requires some arguments to be
passed at the time of calling.
Functions in Python
13
▪ You can call a function by using the following types of formal
arguments −
Function ▪ Required arguments
Parameters ▪ Keyword arguments
and Arguments ▪ Default arguments
▪ Variable-length arguments
Functions in Python
14
▪ Required arguments are the arguments
passed to a function in correct positional
Required order.
arguments ▪ Here, the number of arguments in the
function call should match exactly with
the function definition
Functions in Python
15
# Function definition is here
def printme( str ):
"This prints a passed string into this
function"
print (str)
return;
Example # Now you can call printme function
printme()
======================= RESTART: F:/Python
ex/fnex3.py =======================
Traceback (most recent call last):
File "F:/Python ex/fnex3.py", line 8, in <module>
printme()
TypeError: printme() missing 1 required positional argument:
'str' Functions in Python
>>>
16
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print(str)
return;
Example # Now you can call printme function
printme("Python")
======================= RESTART: F:/Python
ex/fnex3.py =======================
Python
>>>
Functions in Python
17
▪ Keyword arguments are related to the function calls.
▪ When you use keyword arguments in a function call, the
Keyword caller identifies the arguments by the parameter name.
arguments ▪ This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
Functions in Python
18
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print( "Name: ", name)
print("Age ", age)
return
Example # Now you can call printinfo function
printinfo( age=50, name="miki" )
======================= RESTART: F:/Python
ex/fnex6.py =======================
Name: miki
Age 50
>>>
Functions in Python
19
Default ▪ A default argument is an argument that assumes
arguments a default value if a value is not provided in the
function call for that argument.
Functions in Python
20
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return
Example # Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
======================= RESTART: F:/Python
ex/fnex7.py =======================
Name: miki
Age 50
Name: miki
Functions in Python
Age 35
>>>
21
▪ You may need to process a function for more arguments than
you specified while defining the function.
▪ These arguments are called variable-length arguments and
Variable-length are not named in the function definition, unlike required and
default arguments.
arguments def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Functions in Python
# Function definition is here 22
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print("Output is: ")
print(arg1)
for var in vartuple:
print(var)
return;
Example # Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
======================= RESTART: F:/Python
ex/fnex8.py =======================
Output is:
10
Output is:
70
60 Functions in Python
50
23
Thank You
Functions in Python