+ 5

What's the difference between a global variable and a local variable

Definition of Functions, Pls give Examples

17th Jun 2020, 11:01 PM
OSΔSℱ
OSΔSℱ - avatar
8 RĂ©ponses
+ 4
Hi! If you assign a varabel in the top level (modul level) it becoms automatic a global variabel. You can reach this variabel from inside of a function, for example read it’s value. But you can’t assign to it, because then it becomes a local variabel with the same name as the global variabel. So if you want to change the value of the gloabal variabel from inside of a function, you first have to declare it as global in that function. after that, when you change the value from inside the function on the global variabel, it vill not become a local variabel inside the function. The changes will acctually take place even outside the function. From i inside the function you write global x to make x to a global variabel. And if the variable not already exist in the module layer, it will be created. Hope it helped. Regards /Per B
17th Jun 2020, 11:42 PM
Per Bratthammar
Per Bratthammar - avatar
+ 5
A global variable is declared outside of a function and can be used on any function in the program. A local variable is declared inside of a function and can be used only inside that function. For example you could have local variables with exactly the same name used in different functions. ----- x = "global " def foo(): global x y = "local" x = x * 2 print(x) #global * 2 print(y) #local foo() Result: global global local ------ The lines with the # are comments about the solution. Hope it helps !
17th Jun 2020, 11:07 PM
zeldaIsANerd
zeldaIsANerd - avatar
+ 3
OSΔSℱ 1. A variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function. x = "global" def fun(): print("x inside:", x) fun() print("x outside:", x) Output: x inside: global x outside: global 2.A variable declared inside the function's body or in the local scope is known as a local variable. def fun(): y = "local" fun() print(y) Output: NameError: name 'y' is not defined
18th Jun 2020, 1:11 AM
Indira
Indira - avatar
+ 3
Thank you Very much Per Bratthammar & Indira & Lamya😉. God Bless you
18th Jun 2020, 7:44 AM
OSΔSℱ
OSΔSℱ - avatar
+ 1
Thank You Very Much zeldaIsANerd
17th Jun 2020, 11:10 PM
OSΔSℱ
OSΔSℱ - avatar
+ 1
𝐊𝐱𝐱𝐛𝐹 𝐆𝐡𝐚đČđšđ„ Most of those answer are in Java and php but thanks for your help
18th Jun 2020, 7:42 AM
OSΔSℱ
OSΔSℱ - avatar
+ 1
If i declare register storage specifier as globally what will happen.
19th Jun 2020, 7:28 PM
Amesh Kumar Reddy
0
😕 I'm confused Amesh Kumar Reddy
19th Jun 2020, 7:29 PM
OSΔSℱ
OSΔSℱ - avatar