Functions in Python
Function
A function is a named sequence of statement(s) that performs a computation. It contains line of code(s) that are executed sequentially from top to bottom by Python interpreter.
Instead of writing a large program we can write small functions as a specific part of program to accomplish the task.
They are the most important building blocks for any software in Python.
Functions can be categorized as belonging to
i. Modules
ii. Built in
iii. User Defined
User defined Function
It is also possible for programmer to write their own function(s). These functions can then be combined to form a module which can then be used in other programs by importing them.
• To define a function keyword def is used.
• After the keyword comes an identifier i.e. name of the function, followed by parenthesized list of parameters and the colon which ends up the line.
• Next follows the block of statement(s) that are the part of function. Statements in a block are written with indentation.
Advantages of Functions:
• Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read, understand and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
Define a Function
the Syntax of function is:
def NAME ( [PARAMETER1, PARAMETER2, …..] ):
statement(s)
# indented (4 space) statement
Note: The first line of function definition, i.e., Line No. 1 is called header and the rest, i.e. Line No. 2 in our example, is known as body.
Consisting of sequence of indented (4 space) Python statement(s), to perform a task.
Example
Let‟s write a function to greet the world:
def sayHello (): # Line No. 1
print( “Hello World!”) # Line No.2
Types of Functions
There are various types of functions variations:
1. User-defined Functions without argument and without return statement
2. User-defined Functions with argument and without return statement
3. User-defined Functions with argument and with return statement
4. User-defined Functions with argument and with multiple return values
User-defined Functions without argument and without return statement
def evenodd():
a=int(input(“enter a number:”)
if a%2==0:
print( a,”is even“)
else:
print( a,”is odd“)
evenodd()
output:
Enter a number:45
45 is odd
User-defined Functions with argument and without return statement
def evenodd(a):
if a%2==0:
print( a,”is even“)
else:
print( a,”is odd“)
>>> evenodd(45)
45 is odd
>>> evenodd(66)
66 is even
User-defined Functions with argument and with return statement
def evenodd(a):
if a%2==0:
return ” even”
else:
return ” odd”
>>> x=evenodd(34)
>>> print( x )
even
User-defined Functions with argument and with multiple return statement
def calc (a, b) :
add=a+b
mul=a *b
div=a/b
return add, sub, mul, div
x = int (input ( “Enter a number1”))
y = int (input ( “Enter a number2”))
a,s,m,d=calc(x,y)
print( “sum is “,a)
print( “difference is”,s)
print( “multiplication”,m)
print( “quotient is”, d)
Parameters and Arguments in Functions
• When we write header of any function then the one or more values given to its parenthesis ( ) are known as parameter.
• These are the values which are used by the function for any specific task. While argument is the value passed at the time of calling a function.
• Formal parameters are said to be parameters and actual parameters are said to be arguments.
DIFFERENT WAYS OF USING ARGUMENTS
1. Positional Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable length Arguments
1. Positional Arguments
The arguments are passed in correct positional order to function according to the variables in function header.
def subtract(a,b):
print(a-b)
>>> subtract (200, 100)
100
>>> subtract (100, 200)
-100
2. Default Arguments
This is point to remember This is point to that the default should be given aft default argument.
A default argument is a function parameter that has a default value provided to it. If the user does not supply a value for this parameter, the default value will be used. If the user does supply a
value for the default parameter, the user-supplied value is used.
Eg.
def greet (message, times=1):
print message * times
>>> greet (‘Welcome’) # function call with one argument value
>>> greet (‘Hello’, 2) # function call with both the argument values.
Output:
Welcome
HelloHello
3. Keyword Argument
• This is explicit type of assigning the values to function variable, where we use name of the variable and its value.
• If we change the order of variables still it makes no difference in result.
>>> def wish (name,msg) :
print (“Hello! ” , name, “! ” ,msg, “! “)
wish (name=”Ram” , msg=”Good Evening”)
Hello! Ram ! Good Evening !
wish (msg=”Good Evening” , name=” Ram”)
Hello! Ram ! Good Evening !
4. Variable Length Arguments
• Here any number of Arguments can be passed to function.
• Special symbol * asterik is used to declared it as variable length argument.
def sum(*n):
s=0
for i in n:
s=s+i
print (“The sum = ” , s)
>>>sum ( )
sum =0
>>>sum(10)
sum = 10
>>>sum (10, 20)
sum = 30
>>>sum (10, 20, 30)
sum =60
Scope of a variables
Variables can only reach the area in which they are defined, which is called scope.
Think of it as the area of code where variables can be used.
There are two types of variable scopes :
● Global Scope
● Local Scope
Python supports global variables (usable in the entire program) and local variables. By default, all variables declared in a function are local variables.
Global Scope
With global scope, variable can be used anywhere in the program
eg:
x=50
def test ( ):
print(“inside test x is “, x)
print(“value of x is “, x)
Output:
inside test x is 50
value of x is 50
Local Scope
With local scope, variable can be used only within the function / block that it is created
Eg:
X=50
def test ( ):
y = 20
print(‘value of x is ’, X, ‘ y is ’, y)
test( )
print(‘value of x is ’, X, ‘ y is ‘, y)
On executing the test( ) we will get
Value of x is 50 y is 20
The next print statement will produce an error, because the
variable y is not accessible outside the def()
To access global variable inside the function prefix keyword global with the variable
Eg:
x=50
def test ( ):
global x =5
y =2
print(‘value of x & y inside the function are ‘ , x , y)
print(‘value of x outside function is ‘, x)
This code will produce following output:
Value of x & y inside the function are 5 2
Value of x outside the function is 5
Unsolved questions for Assignment: