2021年3月23日星期二

Why does my function use the local variable instead of the global? [duplicate]

So made a simple example to help better understand scopes for myself.

From what I understand, a variable within a function is local to ONLY that function. If you want to use a variable that's outside of your function that has the same name as a local variable within your function, you can use the global keyword which tells your function to ignore any local variables with that name and only use the global variable.

So this program is supposed to print the Global variables value first, then call the function and print the global variable again since it should ignore the local variable, but it prints the local variable anyway. Python tutor shows me that it completely skips the global statement.

 cheese = 99                  def func():          global cheese          cheese = 100          print(f"Global cheese is {cheese}")                        print(f"Global cheese is {cheese}")      func()  

Output:

Global cheese is 99

Global cheese is 100

Then when I call the function before the print statement, the variable gets changed to the local variable's value.. why is this?

cheese = 99      def func():      global cheese      cheese = 100      print(f"Global cheese is {cheese}")        func()  print(f"Global cheese is {cheese}")  

Output:

Global cheese is 100

Global cheese is 100

https://stackoverflow.com/questions/66773684/why-does-my-function-use-the-local-variable-instead-of-the-global March 24, 2021 at 09:53AM

没有评论:

发表评论