Home Backend Development Python Tutorial Detailed explanation of five knowledge points to easily understand the scope of Python

Detailed explanation of five knowledge points to easily understand the scope of Python

Mar 28, 2017 pm 03:09 PM

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles