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
| # -*- coding: utf-8 -*-
# Python 3
x = "a" # (1) global scope
y = "y"
def main(): # {
x = 0 # (2) local/main scope
def change_local_x(): # { local/main scope
value = 1
x = value # (3) initialization = implicit local
print("change_local_x() {!r}".format(x))
# }
def change_nonlocal_x(): # { local/main scope
nonlocal x # (2)
value = 1
x = value
print("change_nonlocal_x() {!r}".format(x))
# }
def change_global_x(): # { local/main scope
global x # (1) explicit global
value = "b"
x = value
print("change_global_x() {!r}".format(x))
# }
def print_nonlocal_or_global_x_y(): # { local/main scope
print("print_nonlocal_or_global_x_y(): {!r}, {!r}".format(x, y)) # implicit (2) nonlocal if exists or (1) global
# }
def print_global_x(): # { local/main scope
global x # explicit global
print("print_global_x(): {!r}".format(x))
# }
print("local x: {!r}".format(x))
print()
print_global_x()
print_nonlocal_or_global_x_y()
print()
change_local_x()
print("local x: {!r}".format(x))
print()
change_nonlocal_x()
print("local x: {!r}".format(x))
print()
change_global_x()
print("local x: {!r}".format(x))
# } main
print("global x: {!r}".format(x))
print("global y: {!r}".format(y))
main()
print("global x: {!r}".format(x))
# global x: 'a'
# global y: 'y'
# local x: 0
#
# print_global_x(): 'a'
# print_nonlocal_or_global_x_y(): 0, 'y'
#
# change_local_x() 1
# local x: 0
#
# change_nonlocal_x() 1
# local x: 1
#
# change_global_x() 'b'
# local x: 1
# global x: 'b' |