Global Variables
global 키워드는 가장 바깥의 이름 공간에 정의된 어떤 이름을 함수 안에서 그대로 쓸 수 있게 하는 키워드입니다.
Variables that are created outside of a function (as in all of the examples above) are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
def를 이용해 function/함수를 만든다.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
파이썬이 보니 들여쓰기에 예민한 친구였다.
x = "awesome"
y = "brazowa"
def myfunc():
x = "fantastic"
print("Python is " + x)
def polish():
y = "nieziela"
print("Tree is "+y)
polish()
print("Tree jest " + y)
myfunc()
print("Python is " + x)
출력
Tree is nieziela
Tree jest brazowa
Python is fantastic
Python is awesome
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc() #해당 function을 실행시키지 않으면 에러!
print("Python is " + x)
Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
일반 변수와 global 변수가 대치되어 있을 때는 global이 이긴다.
'python > w3schools' 카테고리의 다른 글
파이썬 w3schools 정리 (0) | 2021.10.05 |
---|---|
[w3schools] Output Variables - Python Variables (0) | 2021.05.25 |
[w3schools] Assign Multiple Values - Python Variables (0) | 2021.05.25 |
[w3schools] Variable Names - Python Variables (0) | 2021.05.24 |
[w3schools] Python Variables - Python Variables (0) | 2021.05.20 |