User Defined Functions
User Defined Functions
Python includes many built-in functions. These functions perform a predefined task
and can be called upon in any program, as per requirement. However, if you don't find
a suitable built-in function to serve your purpose, you can define one. We will now see
how to define and use a function in a Python program.
Defining a Function
A function is a reusable block of programming statements designed to perform a
certain task. To define a function, Python provides the def keyword. The following is
the syntax of defining a function.
Syntax:
def function_name(parameters):
"function docstring"
statement1
statement2
...
...
return [expr]
The keyword def is followed by a suitable identifier as the name of the function and
parentheses. One or more parameters may be optionally mentioned inside parentheses.
The : symbol after parentheses starts an indented block.
The first statement in this block is an explanatory string which tells something about
the functionality. It is called a docstring and it is optional. It is somewhat similar to a
comment. Subsequent statements that perform a certain task form the body of the
function.
The last statement in the function block includes the return keyword. It sends an
execution control back to calling the environment. If an expression is added in front of
return, its value is also returned.
Given below is the definition of the SayHello() function. When this function is called,
it will print a greeting message.
Example: Function
def SayHello():
""First line is docstring. When called, a greeting message will be displayed""
print ("Hello! Welcome to Python tutorial on TutorialsTeacher")
return
To call a defined function, just use its name as a statement anywhere in the code. For
example, the above function can be called as SayHello() and it will show the following
output.
>>> SayHello()
Hello! Welcome to Python tutorial on TutorialsTeacher
def SayHello(name):
print ("Hello {}!.".format(name))
return
>>> SayHello("Gandhi")
Hello Gandhi!
The names of the arguments used in the definition of the function are called formal
arguments/parameters. Objects actually used while calling the function are called
actual arguments/parameters.
In the following example, the result() function is defined with three arguments as
marks. It calculates the percentage and displays pass/fail result. The function is called
by providing different values on every call.
FunctionTest.py
def result(m1,m2,m3):
ttl=m1+m2+m3
percent=ttl/3
if percent>=50:
print ("Result: Pass")
else:
print ("Result: Fail")
return
Run the above script in IDLE with two different sets of inputs is shown below:
Result:
Enter your marks in physics: 50
Enter your marks in chemistry: 60
Enter your marks in maths: 70
Result: Pass
The following SayHello() function is defined with the name parameter having the
default value 'Guest'. It will be replaced only if some actual argument is passed.
You can call the above function with or without passing a value, as shown below.
>>> SayHello()
Hello Guest
>>> SayHello('Tom')
Hello Tom
The above function is defined to receive two positional arguments. If we try to call it
with only one value passed, the Python interpreter flashes TypeError with the
following message:
>>> AboutMe("Ramesh")
TypeError: AboutMe() missing 1 required positional argument: 'age'
If a function receives the same number of arguments and in the same order as defined,
it behaves correctly.
Python provides a useful mechanism of using the name of the formal argument as a
keyword in function call. The function will process the arguments even if they are not
in the order provided in the definition, because, while calling, values are explicitly
assigned to them. The following calls to the AboutMe() function is perfectly valid.
A user-defined function can also be made to return a value to the calling environment
by putting an expression in front of the return statement. In this case, the returned
value has to be assigned to some variable.
The above function can be called and provided the value, as shown below.
The built-in id() function returns a unique integer corresponding to the identity of an
object. In the above code, id() of x before and after passing to a function shows a
similar value.
>>> x=10
>>> id(x)
1678339376
>>> myfunction(x)
value received: 10 id: 1678339376
If we change the above number variable inside a function then it will create a different
variable as number, which is immutable. However, if we modify a mutable list object
inside the function, and display its contents after the function is completed, the changes
are reflected outside the function as well.
The following result confirms that arguments are passed by reference to a Python
function.
>>> mylist=[10,20,30]
>>> myfunction(mylist)
Modified list inside a function: [10, 20, 30, 40]
>>> mylist
[10, 20, 30, 40]