12. What is the difference between local variable and global variable?
Also give a suitable Python code to
illustrate both. The differences between a local variable and global variable have been given below: S.No. Local Variable Global Variable 1 . lt is a variable which is declared within a lt is a variable which is declared outside all Function or within a block. the functions. 2. lt is accessible only within a function/block lt is accessible throughout the program in program. which it is declared. For example, in the following code x, xCubed are global variables and n and cn are local variables. def cube(n): cn = η * η * n return cn x = l0 xCubed = cube(x) print(x, "cubed 15", xCubed) 13. What is the output of the following code? a = I def f () : a = l0 print (a) Ans. The code will print I on the console (Python shell). 17. Write a Python function to sum aiI the numbers in a list. Sample List: (4, 6, 3, 5, 6) Expected O utput: 24 Ans. def sum (numbers) : total = 0 for x in numbers: total += x return total print (sum( (4, 6, 3, 5, 6))) Computer Science with Python-Xll 21. Write a Python function to check whether a number is perfect or not. According to Wikipedia, in number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Example: The first perfect number is 6, because l , 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( l + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = I + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128. Ans. def perfect_number (n) : sum = 0 for x in range (l, n) : if n % x == 0: sum += x return sum == n print (perfect__number (6) ) 22. Write a Python function that prints the first n rows of Pascal's triangle. Note: Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal. Sample Pascal's triangle:
Each number is the two numbers above it added together.
Ans. def pascal_triangle (n) : trow = [1] y = [0] for x in range (max (n, 0) ) : print(trow) trow=[l+r for l, r in zip(trow+y, y+trow)] return n>=l pascal_triangle(5) 23. Write a Python program to make a chain of function decorators (bold, italic, underline, etc.) in Python. Ans. def make_bold (fn) : def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic (fn) : def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @make_italic @make_underline def hello () : return "hello world" print (hello ()) ## returns "<bxi><u>hello world</ux/ix/b>"