Hi Sajeev,
You asked:
“how does Part B of the code know to pull the data from Part A.”
Good question!
In your function, you have five variables:
food (parameter of the function)
total
i
stock
prices
The first three are called “local variables” because their name is
local to the inside of the function. They only exist while the
function is running.
The last two are called “global variables” because their name exists
outside of the function, they are global to the entire script. Every
function inside the script can see them.
Some languages need you, the programmer, to declare your variables
before you can use them. That tells the interpreter or the compiler
where the variable can be seen and which functions will recognise
that name.
Other languages, like Python, avoid (or mostly avoid) needing to use a
declaration. The interpreter can tell what sort of variable it is by
where it is used. The rules are:
-
if you assign a value to a name at the top level of the script,
outside of any function, it is global variable;
-
if you assign a value to a name inside a function, then by
default it is a local variable;
-
unless you declare it as global inside the function;
-
but if you just use a name without assigning to it, then
Python assumes it is a global variable.
Examples:
# This is outside of any function.
variable = "a global variable"
def function1():
# This is inside a function.
# There is no assignment, so it is treated as global.
print(variable)
def function2():
# This is inside a function.
# There is assignment, so it is treated as local.
variable = "a local variable"
print(variable)
function1() # prints "a global variable"
function2() # prints "a local variable"
These are called “scoping rules” and the we talk about the “scope” of
a variable, which parts of the program can see its value.
Python’s scoping rules are a bit more compilicated that I have said
above. We also have scopes for built-in names, class scopes, scopes for
functions nested inside of other functions, and comprehensions. Don’t
worry about all of those. The three important scopes are:
Sometimes we call this the LGB scoping rule.
Builtins include things like len
, print
, list
etc. These are
technically variables just like the ones you create yourself.