15. What is the output of the following code:
salary = 8000
def printSalary():
salary = 12000
print("Salary:", salary)
printSalary()
print("Salary:", salary)
a. Salary: 12000
Salary: 8000
b. Salary: 8000
Salary: 12000
c. Error
d. None of the above
Answers
Answer:
b.salary 8000
salary 12000
Answer: Option (a) is correct.
Concept:
A function is a code block To execute a function it is required to invoke it. Parameters are data that can be passed into a function. As a result, a function can return data.
Given:
salary = 8000 #global variable
def printSalary():
salary = 12000 #local variable
print("Salary:", salary)
printSalary()
print("Salary:", salary)
Find:
Find the output of the given code.
Solution:
Local variable:
Local variables are variables that are created within a function and are associated with a particular function. Outside of the function, it can't be accessed.
Global variable:
Global variables are variables that are defined outside of any function and are available throughout the program, that is, both inside and outside of each function.
∴ Inside the function, it will take the local variable's value (salary = 12000), and outside the function, it'll take the global variable's value (salary = 8000).
Output:
Salary: 12000
Salary: 8000