Repository navigation
Expand file tree
/
Copy pathlegb.py
More file actions
104 lines (72 loc) · 1.73 KB
/
Copy pathlegb.py
File metadata and controls
104 lines (72 loc) · 1.73 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example code for the LEGB-rule and scopes
"""
# pylint: disable=redefined-outer-name
example_one_x = "global"
def example_one():
"""Exaple 1"""
print("x inside:", example_one_x)
example_one()
print("x outside:", example_one_x)
# skriver ut:
# x inside: global
# x outside: global
# example_two_x = "global"
# def example_two():
# """Exaple 2"""
# example_two_x = example_two_x * 2
# print(x)
# example_two()
# # skriver ut:
# # UnboundLocalError: local variable 'example_two_x' referenced before assignment
# def example_three():
# """Exaple 3"""
# example_three_y = "local"
# example_three()
# print(example_three_y)
# # skriver ut:
# # NameError: name 'example_three_y' is not defined
def example_four():
"""Exaple 4"""
example_four_y = "local"
print(example_four_y)
example_four()
# skriver ut:
# local
example_five_y = "global"
def example_five():
"""Exaple 5"""
example_five_y = "local"
print("y local:", example_five_y)
example_five()
print("y global:", example_five_y)
# skriver ut:
# y local: local
# y global: global
example_six_x = "global"
def example_six():
"""Exaple 5"""
global example_six_x
example_six_x = example_six_x * 2
print("x inside:", example_six_x)
example_six()
print("x outside:", example_six_x)
# skriver ut:
# x inside: globalglobal
# x outside: globalglobal
def outer():
"""Example 7 has local scope acts as an enclosed scope for inner()"""
x = "local"
def inner():
"""Example 7 has local scope"""
nonlocal x
x = "nonlocal"
print("x inner:", x)
inner()
print("x outer:", x)
outer()
# skriver ut:
# x inner: nonlocal
# x outer: nonlocal