Computer Science
What do you understand by local and global scope of variables ? How can you access a global variable inside the function, if function has a variable with same name.
Answer
Local scope — Variables defined within a specific block of code, such as a function or a loop, have local scope. They are only accessible within the block in which they are defined.
Global scope — Variables defined outside of any specific block of code, typically at the top level of a program or module, have global scope. They are accessible from anywhere within the program, including inside functions.
To access a global variable inside a function, even if the function has a variable with the same name, we can use the global
keyword to declare that we want to use the global variable instead of creating a new local variable. The syntax is :
global<variable name>
For example:
def state1():
global tigers
tigers = 15
print(tigers)
tigers = 95
print(tigers)
state1()
print(tigers)
In the above example, tigers
is a global variable. To use it inside the function state1
we have used global
keyword to declare that we want to use the global variable instead of creating a new local variable.
Related Questions
When is global statement used ? Why is its use not recommended ?
Write the term suitable for following descriptions :
(a) A name inside the parentheses of a function header that can receive a value.
(b) An argument passed to a specific parameter using the parameter name.
(c) A value passed to a function parameter.
(d) A value assigned to a parameter name in the function header.
(e) A value assigned to a parameter name in the function call.
(f) A name defined outside all function definitions.
(g) A variable created inside a function body.
What are the errors in following codes ? Correct the code and predict output :
total = 0; def sum(arg1, arg2): total = arg1 + arg2; print("Total :", total) return total; sum(10, 20); print("Total :", total)
What are the errors in following codes ? Correct the code and predict output :
def Tot(Number) #Method to find Total Sum = 0 for C in Range (1, Number + 1): Sum += C RETURN Sum print (Tot[3]) #Function Calls print (Tot[6])