search
HomeBackend DevelopmentPython TutorialDetailed explanation of five knowledge points to easily understand the scope of Python

There are many introductions about Python scope on the Internet, so the article I will share with you today allows you to easily understand Python scope by learning these 5 knowledge points. Friends in need can refer to it. Learn from.

">

1. Block-level scope

Think about whether there will be output when running the following program at this time? Will the execution be successful?

#Block-level scope

if 1 == 1:
name = "lzl"

print(name)


for i in range( 10):
age = i

print(age)

Let’s take a look at the execution results first

C:/Users/L/PycharmProjects/s14/preview/ Day8/Scope/main.py
lzl
9

Process finished with exit code 0

The code is executed successfully, no problem; in Java/C#, execute the above The code will prompt that name and age are not defined, but it can be executed successfully in Python. This is because there is no block-level scope in Python. The variables in the code block can be called externally, so it can run successfully;

2. Local scope

Looking back on the knowledge we have learned before, when we learned functions, the function was a separate scope. There is no block-level scope in Python, but there is a local scope; take a look below Code

#Local scope

def func():
name = "lzl"

print(name)

Run this section Code, think about whether there will be output?

Traceback (most recent call last):
File "C:/Users/L/PycharmProjects/s14/preview/Day8/scope/main.py ", line 23, in
print(name)
NameError: name 'name' is not defined

Running error, I believe everyone can understand this, the name variable is only in The func() function takes effect internally, so it cannot be called globally; make a simple adjustment to the above code and see what the result is?

#Local scope

def func ():
name = "lzl"

func() #Execute function
print(name)

Added a code to the previous code, before printing the variable name , execute the function, will the printing change at this time?

Traceback (most recent call last):
File "C:/Users/L/PycharmProjects/s14/preview/Day8/effect? Domain/main.py", line 23, in
print(name)
NameError: name 'name' is not defined

The execution still reports an error, so go back to the previous sentence Words: Even if the function is executed, the scope of name is only inside the function, and it still cannot be called from the outside; remember the first two knowledge points, and then start to expand the trick

3. Scope Chain

Adjust the function and see what the execution result of the following code is?

#Scope chain

name = "lzl"
def f1():
name = "Eric"
def f2():
name = "Snor"
print(name)
f2()
f1()

If you have learned functions, you must know that Snor will be output after f1() is executed; let’s remember a concept first , there is a scope chain in Python. Variables will be searched from inside to outside. First go to your own scope to find it. You will not go to the superior to find it until you can’t find it and report an error.

4. Ultimate Edition Scope

Okay, enough foreshadowing, the Ultimate Edition is here~~

# Ultimate Edition Scope

name = "lzl"

def f1( ):
print(name)

def f2():
name = "eric"
f1()

f2()

Think Do you want to print "lzl" or "eric" as the final execution result of f2()? Remember your answer. Instead of posting the answer now, take a look at the following code:

#Ultimate Edition Scope

name = "lzl"

def f1():
print(name)

def f2():
name = "eric"
return f1

ret = f2()
ret()

#Output: lzl

The execution result is "lzl". Analyzing the above code, the execution result of f2() is the memory address of function f1, that is, ret=f1; execute ret() is equivalent to executing f1(). When executing f1(), it has nothing to do with f2(). name="lzl" and f1() are in the same scope chain. If there is no variable inside the function, it will be looked for outside, so this The value of the time variable name is "lzl"; if you understand this, then you also know the answer to the ultimate code that the answer was not given just now

# Ultimate Edition Scope

name = "lzl"

def f1():
print(name)

def f2():
name = "eric"
f1()

f2 ()

# Output: lzl

Yes, the output is "lzl", remember that before the function is executed, the scope has been formed and the scope chain has also been generated

5, Sina interview questions

li = [lambda :x for x in range(10)]

Determine the type of li? What type are the elements in li?

print(type(li))
print(type(li[0]))

#
#

You can see that li is a list type and the elements in the list are functions. Then print the return value of the first element in the list. What is the return value at this time?

#lambada interview questions

li = [lambda :x for x in range(10)]

res = li[0]()
print(res )

#Output: 9

liThe return value of the first function is 9, not 0. Remember: the internal code will not be executed before the function is executed; the code in the blog can Practice it yourself and deepen your impression

Summary

The above is the entire content of this article. I don’t know if it can bring some help to everyone’s study and work. If you have any questions, you can Leave messages to communicate.

The above is the detailed content of Detailed explanation of five knowledge points to easily understand the scope of Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool