SoFunction
Updated on 2024-10-28

Python Local Variables and Global Variables Difference Principle Analysis

1. Local variables

name = "Yang Li"
def change_name(name):
  print("before change:",name)
  name = "Hello."
  print("after change", name)
change_name(name)
print("Look outside to see if NAME has changed?",name)

Output:

before change: Yang Li
After change. - Hello.
Check outside to see if name has changed? Yang Li

2、Global variables

NAME = "alex" 
def yangjian():
   global NAME       # It's already declared, NAME is the global variable
   print('1 my name', NAME)
   NAME = "land"     # Modify global variables
   print('2 My Name', NAME)

def qupengfei():
   name = "yang"
   print('3 My Name', NAME)  

yangjian()  
qupengfei()

Output:

1My name. alex  
2My name. land
3My name. yang

######## global variable variable name uppercase
######## Lowercase local variable variable names
#in a function Priority reading of local variables,Can read global variables,Unable to reassign values to global variables;But for variable types,Internal elements can be manipulated;如果in a function有globalKeywords.,A variable is essentially the global one,Readable and assignable

3、nonlocal

name = "Gunnar."

def weihou():
  name = "Chancho."
  def weiweihou():
    nonlocal name  # nonlocal, specifies a higher level variable, if there is none then continue up until you find it
    name = "Calm down."
    print(name)
  weiweihou()
  print(name)

print(name)
weihou()
print(name)
# Gunnar
# Chen Zhuo
# Chen Zhuo
# father's elder brother's wife

Global and Local Variables

Variables defined in a subroutine are called local variables, and variables defined at the beginning of a program are called global variables.
The global variable scope is the entire program, and the local variable scope is the subroutine in which the variable is defined.
When a global variable has the same name as a local variable:
Local variables act within the subroutine in which they are defined; global variables act elsewhere.

Function Return Value

To get the result of a function's execution, you can return the result with the return statement

Caution.

Whenever a function encounters a return statement during execution, it stops execution and returns the result, so it can also be interpreted that the return statement represents the end of the function.
If return is not specified in the function, the return value of the function is None.

nested function

name = "Alex"
def change_name():
  name = "Alex2"
  def change_name2():
    name = "Alex3"
    print("Layer 3 printing",name)
  change_name2() # Calling inner functions
  print("Layer 2 printing",name)
change_name()
print("Outermost printing",name)

This is the whole content of this article.