SoFunction
Updated on 2024-12-20

Python variable scoping example analysis

This article is an example of Python variable scoping. Shared for your reference. The details are as follows:

#coding=utf-8
# Variable scoping
global z # Use global variables
z=1 # Assigning values to global variables
x=99 #x Initialization on global variable declaration
def foo(y): #y and z are assigned in the function: the localized
  # Localized areas
  z=x+y #x is not assigned a value, so it's global
  return z
def bar(y):
  global z
  z=x+y
  return z
print foo(1) # Results = 100
print z #Results=1
print bar(1) # Results = 100
print z # Results = 100

I hope that what I have said in this article will help you in your Python programming.