In this lesson, we will work with the generate()
function and the variables result
and age
. We will also talk about local variables and how it works.
Take the following code as an example:
age = 5
def generate():
return age + 3
result = generate()
When the code runs, the value 8
will be in the result
variable.
The age
variable isn't an argument of generate()
, but you can still see it in the function body. It is because we defined the age
variable before the function call, and the Python interpreter reads the file from top to bottom. The rule applies to other variables as well.
Consider another example:
age = 5
def generate():
age = 10
return age + 3
result = generate()
In this case, the result is the number 13
. The external value age = 5
doesn't affect the function code because we defined the age
in the function body. In this case, it is a local variable, meaning it is not visible outside the function.
Let us explore one last example:
age = 5
def generate():
age = 8
generate()
result = age
The result will be 5
. The local variable we created inside generate()
does not affect the external variable age
. So when we called the function, the external variable age
did not change its value and remained 5
.