Skip to content

Commit 46ccdfb

Browse files
ldkomaxim-belkin
andauthored
08-func.md: Add section on variable scope and local variables (#925)
* Add section on variable scope and local variables * use error not output Co-authored-by: Maxim Belkin <[email protected]> * Tweak wording per Maxim's review Co-authored-by: Maxim Belkin <[email protected]>
1 parent f7cbfd2 commit 46ccdfb

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

_episodes/08-func.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,41 @@ Real-life functions will usually be larger than the ones shown here --- typicall
142142
to a few dozen lines --- but they shouldn't ever be much longer than that,
143143
or the next person who reads it won't be able to understand what's going on.
144144

145+
## Variable Scope
146+
147+
In composing our temperature conversion functions, we created variables inside of those functions,
148+
`temp`, `temp_c`, `temp_f`, and `temp_k`.
149+
We refer to these variables as [local variables]({{ page.root }}/reference.html#local-variable)
150+
because they no longer exist once the function is done executing.
151+
If we try to access their values outside of the function, we will encounter an error:
152+
~~~
153+
print('Again, temperature in Kelvin was:', temp_k)
154+
~~~
155+
{: .language-python}
156+
157+
~~~
158+
---------------------------------------------------------------------------
159+
NameError Traceback (most recent call last)
160+
<ipython-input-1-eed2471d229b> in <module>
161+
----> 1 print('Again, temperature in Kelvin was:', temp_k)
162+
163+
NameError: name 'temp_k' is not defined
164+
~~~
165+
{: .error}
166+
167+
If you want to reuse the temperature in Kelvin after you have calculated it with `fahr_to_kelvin`,
168+
you can store the result of the function call in a variable:
169+
~~~
170+
temp_kelvin = fahr_to_kelvin(212.0)
171+
print('temperature in Kelvin was:', temp_kelvin)
172+
~~~
173+
{: .language-python}
174+
175+
~~~
176+
temperature in Kelvin was: 373.15
177+
~~~
178+
{: .output}
179+
145180
## Tidying up
146181

147182
Now that we know how to wrap bits of code up in functions,

reference.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,10 @@ library
148148
: A family of code units (functions, classes, variables) that implement a set of
149149
related tasks.
150150

151+
local variable
152+
: A variable defined inside of a function, that exists only in the scope of that
153+
function, meaning it cannot be accessed by code outside of the function.
154+
151155
loop variable
152156
: The variable that keeps track of the progress of the loop.
153157

0 commit comments

Comments
 (0)