I'm practicing implementing the Fibonacci sequence using a recursive function
dic = {1: 1,
2: 1}
def pibo(n):
if n in dic:
return dic[n]
else:
out = pibo(n-1) + pibo(n-2)
dic[n] = out
return out
I wonder why we can refer to external variables inside the function without having to do global dic here.
global dictionary python
In Python, a variable declared outside a function is called a global variable (global variable). Global variables are freely accessible outside or inside the function.
In the question code, the dic is a global variable because it is declared outside of the fibo function, so you can access this global variable dic within fibo.
If the dic is declared once more in the pibo as shown below, what is declared inside is the region variable, and the dic of if n indic in the lower line of it represents the region variable.
dic = {1: 1,
2: 1}
def pibo(n):
dic = {1: 0,
2: 1}
if n in dic:
return dic[n]
else:
out = pibo(n-1) + pibo(n-2)
dic[n] = out
return out
The global keyword is not a random keyword, but (1) a keyword that is attached within a function when declaring a global variable within a function, and (2) a keyword that is attached within a function when you want to modify the contents of a global variable within a function.
622 Uncaught (inpromise) Error on Electron: An object could not be cloned
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
575 Who developed the "avformat-59.dll" that comes with FFmpeg?
919 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.