Professional Documents
Culture Documents
Introduction To Data Analysis With Python and R: (CSEN 3135)
Introduction To Data Analysis With Python and R: (CSEN 3135)
• The function int has actually two arguments with the second argument as
base of the number, with default value of 10
def int(s,b=10): # convert a string to a decimal number (by default)
………..
• int(“95”) gives the result 95 (as it is a valid decimal number
• int(“B5”) gives rise to error (as it is not a valid decimal number)
• int(“B5”,16) does not give any error as it takes B5 as a number with base 16
• int(“B5”,16) gives the hexadecimal equivalent of B5 = 181
Default arguments
• Default values must come at the end
• Default values are identified by the position
• Order of the arguments is important
• Example:
• def func(w,x,y,z): # okay, no default values
• def func(w=10,x,y,z): # wrong
• def func(w,x,y=10,z=18): # okay
• func(5,8) => w = 5, x = 8, y = 10, z = 18
• func(5,8,15) => w = 5, x = 8, y = 15, z = 18
• func(5,8,15,38) => w = 5, x = 8, y = 15, z = 38
• Not possible to use default value of y and given value of z by using 3
arguments
Defining a function
• def is used to define a function
• A function can be defined conditionally
if condition:
def func(x,y,z):
…………
else:
def func(x,y,z):
…………
• Function can also be redefined
• Function can be assigned a new name
def func1(x,y,z):
…………
func2 = func1
• Now func2 is another name for func1
• This is required to pass a function as argument of another function (just like a variable)
Function as an argument of another function
• Let us define a function ‘apply’ to apply, n number of times, a function
‘func’ with argument x
• def apply(func,x,n):
ret_val = x
for i in range(n):
ret_val = func(ret_val)
return(ret_val)
• def square(x):
return(x * x)