Advanced Functions ================== Types of Variables ================== -> two types: 1) Local Variables 2) Global Variables Local Variables =============== -> Local variables are also called as "function variables". -> The local variable have the scope within the function. Ex: def function(): x = 10 print(x) print(x) ==> Name error def greetings(): name = "Ajay" #local variable print("Hello",name,",Good Evening!") greetings() # print("Hello",name,",Good Evening!") def wishes(name): print("Hi,",name) wishes("Rk") Note: ===== Python does not support the block variable scope, because it is a dynamically typed language. def f1(): if(True): x = 123 print(x) if(1): print(x) print(x) f1() # print(x) Mutability Vs Immutability ========================== x = 100 y = x # original definitions print(x) print(y) print(id(x)) print(id(y)) x = 200 # re-assignment/ modification print(x) print(y) print(id(x)) print(id(y)) a = [1,3,4,5] print(id(a)) a[2] = 123 print(a,id(a)) a = [1,2,3,4] print(id(a)) Global Variables ================ -> We can define a variable in outside the function and allowed to access in anywhere within the program. x = 123 def f1(): print(x) print(y) def f2(): print(x) print(y) def f3(): print(x*x) print(y) print(x) y = 321 f1() f2() f3() print(y) Q-1: ==== is it possible to define a global variable in inside the function? =================================================================== Ans: Yes. using 'global' keyword def f1(): global x # declaring a global variable x = 123 print(x) # print(x) f1() print(x) Q-2: is it possible to modify the global variable in function? Ans: Yes using global keyword a = 100 # global variable def f1(): # print(a) global a a = 200 print("Inside the function:",a) print("Outside the function:",a) f1() print("After the modification:",a) ================================================== Recursion: ========== the function that calls itself is called "Recursion". Factorial of number using loops: ================================ n = int(input("Enter a value:")) i = n factorial = 1 while i != 0: factorial = factorial * i i = i - 1 print(factorial) using functions: ================ def factorial(n): fact = 1 if n == 0: print("Factorial = ",fact) elif n > 0: i = n while i != 0: fact = fact * i i = i - 1 print("Factorial = ",fact) else: print("Factorial is not possible") factorial(5) ============================================ using Recursion: ================ def factorial(n): if n == 0: fact = 1 else: fact = n * factorial(n-1) return fact result = factorial(5) print(result)