File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments