More On Function
More On Function
Global Variables
'''The variables which are declared outside of function are called global variables
These variables can be accessed in all functions of that module.'''
Out[1]: 'The variables which are declared outside of function are called global variable
s.\nThese variables can be accessed in all functions of that module.'
10
10
10
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[3], line 14
12 #########
13 f1()
---> 14 f2()
777
10
In [5]: d=10
def f1():
global d
d=777 #local variable
print(d)
#####
def f2():
print(d)
#########
f1()
f2()
777
777
100
100
In [7]: '''Note: If global variable and local variable having the same name then we can
access global variable inside a function as follows'''
###############
g=110
def f1():
g=100 #local variable
print(g)
print(globals()['g'])
######
f1()
100
110
In [8]: #Recursive function:
#Write a Python Function to find factorial of given number with recursion.
###########
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
##################
print(f'factorial of {4} is: {factorial(4)}')
print(f'factorial of {5} is: {factorial(5)}')
factorial of 4 is: 24
factorial of 5 is: 120
In [ ]: