FUNCTION Python - 09 - User - DefinedFunctions
FUNCTION Python - 09 - User - DefinedFunctions
to perform specific tasks. Python itself is huge library of built-in functions . These functions perform a
predefined task and can be called upon in any program, as per requirement. But sometimes if you
don’t find such utility function, then it should be built-in by the user. These type of functions are called
user-defined functions.
Class name
Method name
import math Parameter/argument
y = math.sqrt(144.0)
When this statement is executed, the method math.sqrt is called to calculate the square root of
the number contained in the parenthesis (144.00).
Reeta Sahoo & Gagan Sahoo
Defining UDFs
In Python a user-defined function's declaration begins with the keyword def and followed by the
function name and a parentheses ( ).
Function Header
The general format is:
Function body
def function_name (formal_parameters):
...
statements-to-be-executed
...
[return <value(s)>]
Indented area
Here,
The first line of the function definition is called the header; the rest is called the body. The function is declared with
the keyword def. The function header has to end with a colon (:) and the body has to be indented.
The function_name must be a user-defined name or an identifier or variable name.
The format_parameters or arguments (which is placed in square braces ([ ])) are optional. Parameters are specified
within the pair of parentheses in the function definition, separated by commas.
When you provide formal parameters as placeholders they accept values sent to them by the calling function. When
a function is called, the parameters that are passed to it are called actual parameters.
The body of the function consists of one or more Python statements with at least — 4 spaces indentation.
The return statement is optional. If you want to return a value or values, then use return with the value/values by
separating comma.
To end the function body, you have to enter an empty line in interactive mode but this is not necessary in a script
mode.
Declaring UDF at Interactive Mode
A function can be written in an interactive mode or in a script mode. The following function is written in
interactive mode:
>>> def hello():
print (“Hello World!”)
print (“Hello from my function!”)
Calling an UDF
Declaring UDF as Module
The modules in Python have the .py extension. You can create your own Python modules since modules
are comprised of Python .py files.
To create a module,
• Click Ctrl+N to open the python Editor window.
• Type the following:
def hello():
print (“Hello World!”)
print (“Hello from my function!”)
hello() # Calling the module
Function called
• Save the file as Demo.py.
• Execute the file.
To execute the function, you can call the function the name within parentheses. The general
format is:
Press F5 key to execute the Demo.py When we Execution style of hello() function
execute the script with F5 key, it will produce the two
line output immediately at Python Shell window: 2. Control transferred into function
Hello World!
Hello from my function!
def hello() :
3. Function body statements
How does the function executed? executed
def Add_TwoNum():
X = int(input("Enter first number: "))
Y = int(input("Enter second number: "))
Result = X + Y 3. Function body statements executed
Add_TwoNum()
1. Main program execution started here
Output:
Save the file as Test.py and Press F5 key and do the following at interactive mode:
>>> Add_TwoNum()
Enter first number: 34
Enter second number: 51
Reeta Sahoo & Gagan Sahoo
The sum of 34 and 51 is 85
Using import statement
You can use any Python source file as a module by executing an import statement in some other
Python source file or in interactive mode. To import our previously defined module Test we type the
following in the Python interactive prompt.
Here, import Test imports the module Test and creates a reference to that module in the current
namespace. From the caller, objects in the Test module are only accessible when prefixed with
<module_name> via dot notation (.) as shown in the figure given below:
Python has the provision to import entire module under an alternate name. The syntax is:
import <module_name> as <alt_name>
For example:
>>> import Test as T # T as alternate name of the module pandas
>>> T.Add_TwoNum()
Enter first number: 34
Enter second number: 51
The sum of 34 and 51 is 85
Let us see a simply example to calculate sum of two numbers using a function called Add_TwoNum():
def Add_TwoNum():
X = int(input("Enter first number: "))
Y = int(input("Enter second number: "))
return X + Y Returns the sum of X and Y
Result = Add_TwoNum()
print ("The sum is:", Result)
Enter first number: 34
Enter second number: 51
The sum is: 85 Reeta Sahoo & Gagan Sahoo
Returning more than one values
We can return more than one value from a function. The objects, after the return keyword, are
separated by commas. For example, suppose a list called Marks contains five subject marks like
[98, 67, 87, 89, 87] and you want to find the total (MarkSum) and percentage (MarkPer) of a
student’s marks using function by returning more than one value.
So the program code is:
Rewrite the following code after removing the syntactical errors (if any). Underline each
correction.
def add(j):
if (j >= 4):
j=j*j
return j
else:
j = j*2;
return j
def main():
i=4
a=add(4)
print("The value of a is: %d" %a)
main() Reeta Sahoo & Gagan Sahoo
Function Arguments
Parameters are the variables that are defined or used inside parentheses while defining a function,
whereas arguments are the value passed for these parameters while calling a function. Arguments are the
values that are passed to the function at run-time so that the function can do the designated task using
these values.
Function Parameters
Function body
def function_name ( arg1, arg2, …. ):
...
statements-to-be-executed
...
[return <value(s)>]
..........................................
..........................................
Function Arguments
Or
# Defining a function first to return the value of parameter
def ShowMessage(Msg) : # A function with a parameter
return Msg
# Calling the function and supplying arguments
print ("Message is:", ShowMessage("Hello Friends!")) # Calling function with argument "Hello Friends!"
Message is: Hello Friends!
Reeta Sahoo & Gagan Sahoo
Try this:
Find out the error, if any, in the following program and Rewrite the following code in Python after
write the correct line of code. removing all syntax error(s). Underline each
def sum( arg1, arg2 ): correction done in the code.
total = arg1 + arg2; def Sum(Count) #Method to find sum
print ("Inside the function local total : ", total) S=0
return total; for I in Range(1, Count+1):
def main(): S+=1
n1=int(input("First value is:")) RETURN S
n2=int(input("Second value is :")) print Sum[2] #Function Calls
sum(n1); print Sum[5]
print ("The sum is:", total)
main()
Write the output of the following program: Rewrite the following Python program after
def func(x, y = 10): removing all the syntactical errors (if any),
if ( x % y == 0): underlining each correction:
x=x+1 def checkval:
return x x = input("Enter a number")
else: if x % 2 = 0 :
y=y–1 print (x,"is even")
return y else if x<0 :
def main(): print (x,"should be positive")
p, q = 20, 23 else ;
q = func (p, q) print (x,"is odd“)
print("%d \t %d" % (p, q))
p = func(q);
print("%d \t %d" % (p, q))
q = func(p);
print("%d \t %d" % (p, q)) Reeta Sahoo & Gagan Sahoo
main()
Programming example : Fibonacci numbers
Write a program to create a module called Fibonacci.py with two function definitions to find the
Fibonacci series up to n. The two function definitions are:
def fibnos1(n) to write Fibonacci series up to n
def fibnos2(n) which return Fibonacci series up to n
Note. n is the parameter whose Fibonacci series will be generated.
In Python interactive mode, find the Fibonacci series for 100 implementing two function definitions.
# Fibonacci.py
# Two Fibonacci numbers module
def fibnos1(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ') # prints each number
a, b = b, a+b
print()
def fibnos2(n): # return Fibonacci series up to n
series = [] # a list
Output:
a, b = 0, 1
while b < n: >>> import Fibonacci as F
>>> F.fibnos1(100)
series.append(b) # Nos. are appended into a list
1 1 2 3 5 8 13 21 34 55 89
a, b = b, a+b >>> F.fibnos2(100)
return series [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Programming example : Convert Celsius temperature to Fahrenheit.
Write a program to convert Celsius temperature to Fahrenheit. The function should pass the Celsius
value as required argument.