-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23 - scope.py
More file actions
80 lines (47 loc) · 1.41 KB
/
23 - scope.py
File metadata and controls
80 lines (47 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Scope
"""A variable is only available from inside the region it is created. This is called scope."""
# Local Scope
"""A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function."""
import platform
def myfunc():
x = 300
print(x)
myfunc()
# Function inside a function
"""As explained in the example above, the variable x is not available outside the function,
but it is available for any function inside the function:"""
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
# Global scope
"""A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Global variables are available from within any scope, global and local"""
x = 300
def myfunc():
print(x)
myfunc()
print(x)
# Global keyword
"""If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.
The global keyword makes the variable global"""
def myfunc():
global x
x = 300
myfunc()
print(x)
# also use the global keyword if you want to make changes to a global var inside a function
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
# Modules
# Using the dir() function
"""There is a built-in function to list all the function names (or variable names) in a module. The dir() function:"""
x = dir(platform)
print(x)