Computer Science
Assertion (A): Variables declared inside a function are local to that function by default.
Reasoning (R): A function can access global variables if they are explicitly declared with the global keyword inside the function.
Answer
Both A and R are true, and R is the correct explanation of A.
Explanation — By default, variables declared inside a function are local to that function, meaning their scope is limited to the function itself. However, a function can access and modify global variables only if they are explicitly declared with the global keyword inside the function. Otherwise, the function will treat the variable as local.
Related Questions
The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.
def swap_first_last(tup) if len(tup) < 2: return tup new_tup = (tup[-1],) + tup[1:-1] + (tup[0]) return new_tup result = swap_first_last((1, 2, 3, 4)) print("Swapped tuple: " result)What will be the output of the following code ?
c = 10 def add(): global c c = c + 2 print(c, end = '#') add() c = 15 print(c, end = '%')- 12%15#
- 15#12%
- 12#15%
- 12%15#