Skip to content

Commit 515d1b4

Browse files
added a demo of keyword scope
1 parent 946a257 commit 515d1b4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

week-02/keyword_scope_demo.txt

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# we define a variable in the global scope
2+
In [28]: a = 5
3+
4+
# use that variable in a fucntion
5+
In [29]: def add(x):
6+
....: return x + a
7+
8+
# call the function -- a is used.
9+
In [30]: add(3)
10+
Out[30]: 8
11+
12+
# change a
13+
In [31]: a = 12
14+
15+
# now what?
16+
In [32]: add(3)
17+
Out[32]: 15
18+
# the new a is used
19+
20+
# but what if I don't want the results to depend on what a gets re-set to.
21+
# but I don't want a constant, either.
22+
23+
# set a keyword argument:
24+
In [34]: def add(x, a=a):
25+
return x + a
26+
....:
27+
28+
# try it:
29+
In [35]: add(3)
30+
Out[35]: 15
31+
# it used the last a value
32+
33+
# reset a
34+
In [36]: a = 100
35+
36+
# try it
37+
In [37]: add(3)
38+
Out[37]: 15
39+
40+
# still using that earlier value!
41+
42+
## Lesson: the keyword arguments are evaluted _when the function is defined_, NOT when it is called.
43+
44+

0 commit comments

Comments
 (0)