Ask questions about using the python global keyword. Why can you refer to function external variables when you do not declare global?

Asked 2 years ago, Updated 2 years ago, 103 views

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

2022-09-20 19:03

1 Answers

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.


2022-09-20 19:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.