Functions
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.
Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
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 - the documentation string
of the function or docstring.
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.
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Creating a Function
In Python a function is defined using the def keyword:
Example1:
def my_function( ):
print("Hello from a function")
def printme( str ):
"This prints a passed string into this function"
print (str)
return
Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:
Example:
def my_function(fname):
print(fname + " References")
my_function("Email")
my_function("Tobias")
my_function("Linus")
Example:
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments
does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Default Parameter Value
The following example shows how to use a default parameter value. If we call the function
without argument, it uses the default value:
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function. E.g. if you send a List as an argument,
it will still be a List when it reaches the function:
Example
def my_function(fruits):
for x in fruits:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Passing String as an Argument
Python program to pass a string to the function
# function definition: it will accept
# a string parameter and print it
def printMsg(str):
# printing the parameter
print str
# Main code
# function calls
printMsg("Hello world!")
printMsg("Hi! I am good.")
Output
Hello world!
Hi! I am good.
Passing Tuple as an Argument:
def func(myTuple):
myTuple = first, second
return first
#Driver Code
myTuple = (2,3)
#function call 1
print(func(myTuple))
#function call 2
print(func((2, 3)))
Copy
Def tup(a):
For i in a:
Print(i)
Tup((2,3,4,5,6))
Passing Dictionary:
Def dict(a):
For I in a:
Print(I,”:”,a [I])
Dict({1:”one”,2:”two”,3:”three”})
#immutable property
#int,float tuple are immutable
num=51
print("Id is",id(num))
print("class is",type(num))
print("value is",(num))
#value of num is changed
num=501
print("Id is",id(num))
print("class is",type(num))
print("value is",(num))
Output:
*******************************************************
Mutable Properties:
#list,dictionary are mutable
#mmutable property
#id same value changed
l=[10,20,30]
print("Id is",id(l))
print("class is",type(l))
print("value is",l)
print("After changing list elements")
l[2]=40
print("Id is",id(l))
print("class is",type(l))
print("value is",l)
O/P:
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Program1:
Simple Interest Calculation by Function
# Python3 program to find simple interest
# for given principal amount, time and rate of interest.
def simple_interest(p,t,r):
print('The principal is', p)
print('The time period is', t)
print('The rate of interest is',r)
si = (p * t * r)/100
print('The Simple Interest is', si)
return si
# Driver code
simple_interest(8, 6, 8)
Program 2:
# Python program to find Area of a circle
def findArea(r):
PI = 3.142
return PI*(r*r);
# Driver code
print("Area of circle is: " ,findArea(5));