W3schools - Python_Scope / Module
찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요
Scope
Var is only available from inside the region it is created. This is called scope
Local scope
Var created inside a func belongs to the local scope of that func, and can only be used inside that func
Global scope
Var created in the main body of the Python code is a global var and belongs to the global scope
Global var are available from within any scope, global and local
Naming
If operate with the same var name inside and outside of a func, Python will treat them as two separate vars, one available in the global scope and one available in the local scope
Global keyword
If you need to create a global var, but are stuck in the local scope, can use the global
It makes the var global, also, if you want to make a change to a global var inside a func
def func():
global x
x = 300
func()
print(x) # output 300
Module
Consider a module to be the same as a code library
A file containing a set of funcs you want to include in app
When using a func from a module, use the syntax : module_name.func_name
The module also can contain vars of all types
# Save this code in a file name mymodule.py
def greeting(name):
print(“Hello ” + name)
person = {“name” = “John”, “age” = 16}
# other file
import mymodule as mm # can create an alias when import a module
mm.greeting(“Sponge”) # output “Hello Sponge”
print(mm.persion[“age”]) # output 16
Built-in modules
There are several built-in modules in Python, which you can import whenever you like
import platform
# built-in func to list all the func names (or var names) in a module
x = dir(platform)
print(x)
# Can choose to import only parts from a module
from platform import system # When importing using the from
x = system() # don’t use the module name when referring to elements in the module
print(x) # output Darwin