(3) Develop programs to learn concept of
1) Functions Scoping,
2) An example of a Recursive Function to find the factorial of a number and3) List Mutability:
A) Copying Mutable Objects by Reference
B) Copying Immutable Objects
C) Immutable Object Changing Its Value
# LAB-3 function scoping
a='string (Global)' #global
def func1():
a='string within the function (Local)' #local
print("print from func1:",a)
func1()
#here variable a within a the function is printed
print("print from outside:",a)
#while here, variable outside the function is printed
def func2():
global b
b = "global string"
func2()
print("print from outside:", b)
#this is possible because string is declared global
print()
#recursion
# An example of a recursive function to # find the factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 5
print("The factorial of", num, "is=", calc_factorial(num))
#Lab-3
#Copying Mutable Objects by Reference
values = [4, 5, 6]
values2 = values
print("Memory Address=",id(values))
print("Memory Address=",id(values2))
values.append(7)
print(values is values2)
print(values)
print(values2)
#Copying Immutable Objects
text = "Python"
text2 = text
print("Memory Address=",id(text))
print("Memory Address=",id(text2))
print(text is text2)
print()
text += " is awesome"
print("Memory Address=",id(text))
print("Memory Address=",id(text2))
print(text is text2)
print()
print(text)
print(text2)
#Immutable Object Changing Its Value
skills = ["Programming", "PRIME", "GTU"]
person = (129392130, skills)
print(type(person))
print(person)
skills[2] = "Maths"
print(person)
No comments:
Post a Comment