-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobalLocalScopes.py
More file actions
executable file
·84 lines (60 loc) · 1.06 KB
/
GlobalLocalScopes.py
File metadata and controls
executable file
·84 lines (60 loc) · 1.06 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 26 23:25:14 2021
@author: maherme
"""
#%%
a = 10
def my_func(n):
print('global a:', a)
c = a ** n
return c
res = my_func(2)
print(res)
#%%
def my_func(n):
a = 20
c = a ** n
return c
print(a)
res = my_func(2)
print(res)
print(a) # a is not modified because a inside my_func is in other scope, is not global
#%%
def my_func(n):
global a # Now a is global, it will change
a = 20
c = a ** n
return c
print(a)
res = my_func(2)
print(res)
print(a)
#%%
def my_func():
global var
var = 'hello world'
return
# print(var) # This will fail due to var is not defined
my_func()
print(var)
#%%
def my_func():
global a
a = 'hello'
print('global a:', a)
my_func()
print(a)
#%%
a = 10
def my_func():
print('global a:', a) # fails because a is local here, but is declared after using.
a = 'hello world' # a is declared here
print(a)
my_func()
#%%
for i in range(10):
x = 2 * i
print(x) # Notice x exists outside the for loop.
#%%