Functions 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Functions

In [1]: '''A simple program'''


def display12():
print('Hello good Morning!')

#Now we can call the above function


display12()

Hello good Morning!

In [2]: '''
# We can even call the function inside another function
'''
def wish():
display12()
print('How are you?')
###############
wish()

Hello good Morning!


How are you?

In [3]: '''
# Defining a function using parameters
'''
def wish(name):
print('Hello', name, 'good morning')

wish('Rajesh')
wish('Sachin')
'''
# the new wish function overwrited the previous wish function
'''

Hello Rajesh good morning


Hello Sachin good morning
Out[3]: '\n# the new wish function overwrited the previous wish function\n'

In [4]: # Write a function to take a number as input and print its square value.
def my_square(value):
print('The square of the number is:', value**2)
##############
my_square(4)
my_square(5)
my_square(6)
#####calculate the square of first 10 numbers (0-9) using for loop and my_square()
#function
# for i in range(10):
# my_square(i)

The square of the number is: 16


The square of the number is: 25
The square of the number is: 36
In [5]: def my_square(value):
sq_val=value**2
return sq_val
##############
my_square(4)
print(my_square(4))

16

In [6]: '''
# Write a function to accept 2 numbers as input and return sum.
'''
def my_add(val1, val2):
val3=val1+val2
return val3
#my_add(2) # we should assign two parameters
print(my_add(2,4))

In [7]: # default return none


def my_fun():
print('Hello')
print(my_fun())

Hello
None

In [8]: '''
# We can use branching statements, loops or whatever we learned so far
#inside the functions
'''
#Write a function to check whether the given number is even or odd?
def even_odd(num):
if num%2==0:
print('The number', num, 'is even')
else:
print('The number', num, 'is odd')
###############
even_odd(3)
even_odd(10)

The number 3 is odd


The number 10 is even

In [9]: '''
# Write a function to find factorial of given number?
'''
def my_fact(num):
fact=1
for i in range(1, num+1):
fact*=i
print(fact)
####################
my_fact(6)

720
In [10]: '''
# Write a function to find factorial of given number?
'''
def my_fact(num):
fact=1
i=1
while i<=num:
fact*=i
i+=1
print(fact)
################
my_fact(4)

24

In [11]: '''
#A function can return any number of values.
'''
def my_stat(A):
"""
A is list and the function returns maximum and minimum
vale of a list
"""
maximum=max(A)
minimum=min(A)
return maximum, minimum
print (my_stat.__doc__) # printing the doc string of a function
A=[-1,2,3,10]
print(my_stat(A)) # multiple outputs are return as tuple
t1,t2=my_stat(A)
print(t1)
print(t2)

A is list and the function returns maximum and minimum


vale of a list

(10, -1)
10
-1

In [12]: '''
positional arguments:
These are the arguments passed to function in correct positional order.
'''
def my_fun(a,b):
print(a-b)
my_fun(10,20) # result is -10
my_fun(20,10) # result is 10
#argument position changes the final result

-10
10

In [13]: '''
Keyword arguments
We can pass argument values by keyword i.e by parameter name
'''
def wish(message, name):
print('Hello', name, message)
wish(message='how are you?', name='Rajesh')
wish(name='Rajesh', message='how are you?')

# Here the order of arguments is not important but number of arguments must be matc

Hello Rajesh how are you?


Hello Rajesh how are you?

In [14]: '''
We can use both positional and keyword arguments simultaneously. But first we
have to take positional arguments and then keyword arguments, otherwise we will get
Syntax error.
'''
def wish(name, message):
print('Hello', name, message)

wish("Durga","Good Morning") # fitst argument is name, second one is message


wish("Good Morning","Durga") # fitst argument is name, second one is message
wish("Durga",message="GoodMorning")
#wish(message="GoodMorning", "Durga")
'''
Error: positional argument follows keyword argument
'''

#wish(name="GoodMorning", "Durga")

Hello Durga Good Morning


Hello Good Morning Durga
Hello Durga GoodMorning
Out[14]: '\nError: positional argument follows keyword argument\n'

In [15]: '''
Default Argument
Sometimes we can provide default values for our positional arguments
'''
def wish(name='Something'):
print('Hello', name,'Good Morning')
wish('Rajesh')
wish() # If we are not passing any name then only default value will be considered

Hello Rajesh Good Morning


Hello Something Good Morning

In [16]: '''
After default arguments we should not take non default arguments
'''
def wish(name="Guest",msg="Good Morning"):
print('Hello', name,msg)
wish()
wish(name='Rajesh', msg='how are you?')

Hello Guest Good Morning


Hello Rajesh how are you?
In [17]: def wish(name,msg="Good Morning"):
print('Hello', name,msg)
#wish() # error
wish('Raj')
wish(name='Rajesh', msg='how are you?')

Hello Raj Good Morning


Hello Rajesh how are you?

In [18]: def wish(msg="Good Morning",name):


print('Hello', name,msg)
#wish() # error
wish('Raj')
wish(name='Rajesh', msg='how are you?')

Cell In[18], line 1


def wish(msg="Good Morning",name):
^
SyntaxError: non-default argument follows default argument

In [19]: def wish(name='Rajesh',"Good Morning"):


print('Hello', name,msg)
# wish() # error
wish('Raj')
wish(name='Rajesh', msg='how are you?')

Cell In[19], line 1


def wish(name='Rajesh',"Good Morning"):
^
SyntaxError: invalid syntax

In [20]: '''
Variable Length Arguments
Sometimes we can pass variable number of arguments to our function,such type of
arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows def f1(*n)

We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

'''
def sum(*n):
total=0
for n1 in n:
total=total+n1
print('the sum is', total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)
sum(10,20,30,40,50,50)
the sum is 0
the sum is 10
the sum is 30
the sum is 100
the sum is 200

In [21]: '''
# We can mix variable length arguments with positional arguments.
'''
def my_fun(n1,*s):
print(n1)
total=0
for s1 in s:
total=total+s1
print('the sum is:',total)
# my_fun(10)
#
#my_fun()
my_fun(10,20,30)

10
the sum is: 50

In [22]: '''
After variable length argument, if we are taking any other arguments then we should
provide values as keyword arguments.
'''
def my_fun(*s,n1):
print(n1)
total=0
for s1 in s:
total=total+s1
print('the sum is:',total)
my_fun(10,20, n1=30)
#my_fun(10,20,30) # error

30
the sum is: 30

In [23]: '''
We can declare key word variable length arguments also. For this we have to use
**
'''
def display(**kwargs):
for k,v in kwargs.items():
print(k,'=',v)
display(n1=10, n2=20)
display(n1=10, n2=20, n3=25)

n1 = 10
n2 = 20
n1 = 10
n2 = 20
n3 = 25

In [24]: def display(**kwargs):


print(kwargs)
display(n1=10, n2=20)
display(n1=10, n2=20, n3=25)

{'n1': 10, 'n2': 20}


{'n1': 10, 'n2': 20, 'n3': 25}

In [25]: #Check the valid function call for the below function definition.
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
#####
f(3,2)
f(10,20,30,40)
f(25,50,arg4=100)
f(arg4=2,arg1=3,arg2=4)
f()

3 2 4 8
10 20 30 40
25 50 4 100
3 4 4 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[25], line 9
7 f(25,50,arg4=100)
8 f(arg4=2,arg1=3,arg2=4)
----> 9 f()

TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2'

In [ ]:

You might also like