Functions
Nihar Ranjan Roy
[email protected], [email protected] Department of Computer Science and Engineering
GD Goenka University, Gurugram
Home Page:https://sites.google.com/site/niharranjanroy/
Outline
1 Functions
2 Syntax
3 Function with default arguments
4 Functions with keyword arguments
5 Scope of variables
6 Returning multiple values from a function
7 Recursive function
8 Lambda Function
Functions
Functions
Functions are a set of instructions grouped together that perform special task and are called by an identifier assigned to it called function name. Functions has several advantages
Code becomes smaller
Readability
Modularity Re-usability
Syntax
Syntax
The keyword def introduces a function definition.
It must be followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and must be indented.
def name_of_function(Parameters):
"""docstring"""
statement1\\ statement2\\
.\\
.\\
Syntax
Problem
Write a function for finding sum of the number within a range specified by the user.
sum(5,7)
sum is 18 (5+6+7=18)
Syntax
Solution
#sum of number in a range
def sumrange(a,b):
sum=0
for i in range(a,b+1):
sum=sum+i
return sum
#call function
print("Sum is ",sumrange(5,7))
Syntax
Problem
Write a program to generate Fibonacci series of n terms whose first two terms are 0 and 1.
Syntax
Solution
def fib(n): # argument to the function
"""function to generate Fibonacci series upto n"""
a, b = 0, 1 while a <n:
print(a, end=' ') a,b=b,a+b
print()
Function with default arguments
Functions with default arguments
It is possible to assign default value to parameters in Python, if no parameter is passed then default value is used.
#function with default arguments def sum(a=4,b=5):
return(a+b)
#calling function
print(sum(2,2)) # calling with parameters
print(sum()) #calling without parameters
Functions with keyword arguments
Functions with keyword arguments
If a programmer knows the parameter names,he/she can use it to pass arguments to functions.
def display( Name, Mobile):
print(Name, "has mobile number", Mobile)
#call to function
Functions with keyword arguments
Precautions:Functions with keyword arguments
def display( Name, Mobile):
print(Name, "has mobile number", Mobile)
1 A positional argument cannot follow a keyword argument.Example
display(Mobile=1234567,’Nihar’)
2 Cannot duplicate an argument by both specifying it as keyword
argument and positional argument. Example display(’Nihar’,Name=’Ranjan’)
Scope of variables
Scope of variables in python I
#this program demonstrates variable scope
var1=4 def func():
var1=7
print("inside func()"+str(var1))
print("outside function"+str(var1)) func()
Scope of variables
Scope of variables in python II
——–output————– outside function4 inside func()7 outside function4
Scope of variables
Scope of variables in python III
#this program demonstrates variable scope
var1=4 def func():
global var1 var1=7
print("inside func()"+str(var1))
print("outside function"+str(var1)) func()
Scope of variables
Scope of variables in python IV
——–output————– outside function4 inside func()7 outside function7
Scope of variables
Problem
Write a function to accept an integer and tell if it is an Armstrong number or not.
Example: 153, has 3 digits
so (1)3+ (5)3+ (3)3 = 1 + 125 + 27 = 153
Returning multiple values from a function
Returning multiple values from a function
#returning multiple values from function
def compute (no1,no2):
return no1+no2, no1-no2
#calling function sum,diff =compute(7,5)
print("sum and difference of two
numbers is ",sum, "and ",diff)
Output:
sum and difference of two numbers is 12 and 2
Recursive function
Recursive function
if a function calls itself again and again till a terminating condition is reached is called recursive function.
#recursive factorial of number def factorial(no):
if no==1:
return 1
return no*factorial(no-1)
#call function factorial
no=5
Lambda Function
Lambda Function
These are also know as anonymous functions. Such functions are not
bound to any name
#lambda function
cube=lambda x:x*x*x #define lambda function print(cube(3)) #call lambda function
Note:
Lambda function doesnot contain return statement
It contain single statement/ expression in its body.
Lambda Function
Problem
Lambda Function
Solution
def DecimalToBinary(n):
if n>0:
print(n%2,end=' ') n=n//2
DecimalToBinary(n)
#calling function
print("MSB is on right") DecimalToBinary(7)
print("\n")
DecimalToBinary(17)
print("\n")
DecimalToBinary(27)
———–OUTPUT——————-MSB is on right 1 1 1
1 0 0 0 1 1 1 0 1 1
Lambda Function
User defined module
Its a two step process
1 User the import keyword to import the previously defined module
example ”UserModule”
import UserModule
2 To user function or variables from the module prefix it with the name
of the module
User defined module
Problem
Create user define module named ”UserModule” and inside that create a function DToB for converting a decimal number to binary. Also using this module convert an integer number to binary
User defined module
Solution-I
def DToB(n): s=""
while n>0:
s=s+str(n%2) n=n//2
print(s[::-1])
if __name__=="__main__":
n=int(input("Please enter an integer"))
User defined module
Solution-II
import UserModule
print("Using a user defined module") UserModule.DToB(23)
———–OUTPUT——————-Using a user defined module 1 1 1 0 1
Exercises
Exercises I
1. Write a function to find reverse of an integer number.
2. List the steps involved in creating a user defined module and use it.
3. On the basis of following function
def display(Name, Mobile):
print(Name, ”has mobile number”,Mobile)
What will be the output for the following calls? Give your comments wherever necessary
i. display(Mobile=1234567890,Name=’Nihar’)
ii. display(Mobile=1234567890,’Nihar’)
iii. display(’Nihar’,Mobile=1234567890)
iv. display(Mobile=1234567890,’12343454’)
Exercises
Exercises II
4. What do you understand by scope of a variable? Explain usage of
global keyword with an example
5. Write a function to convert a number from binary to decimal.
6. Write a recursive function to printnth fibonacci series term.
7. Is it possible in python to return multiple values from a function?
Illustrate it with an example.