The problem of exec scope in python

I am a rookie. I used the exec method when reading a crawler textbook, but there was one thing I didn"t understand, so I simplified that paragraph into a function.
in the first case, the name variable is connected with both ends with +, the second is written directly in a string, and the third is printed directly
does not understand the difference between the first two, isn"t it all a string? By the way, I"d like to ask you about the scope of exec. My heart is so tired
ask the kind-hearted person, thank you very much

def func ():

list = ["a", "b", "c"]

x = 1
for a in list:
    name = "number" + str(x)  -sharp 
    exec(name + "=a")  -sharp 
    exec("print(" + name + ")")
    x += 1

func ()

< H1 > a < / H1 > < H1 > b < / H1 > < H1 > c < / H1 >

def func ():

list = ["a", "b", "c"]

x = 1
for a in list:
    name = "number" + str(x)  -sharp 
    exec(name + "=a")  -sharp 
    exec("print(name)")
    x += 1

func ()

< H1 > number1 < / H1 > < H1 > number2 < / H1 > < H1 > number3 < / H1 >

def func ():

list = ["a", "b", "c"]

x = 1
for a in list:
    name = "number" + str(x)  -sharp 
    exec(name + "=a")  -sharp 
    print(name)
    x += 1

func ()

< H1 > number1 < / H1 > < H1 > number2 < / H1 > < H1 > number3 < / H1 >
Mar.25,2022

by default, the scope of exec is within the scope of the current statement block. In the first code, the value of name is 'number' + str (x) . It is better to replace name with its value

.
def func():
    list = ['a', 'b', 'c']

    x = 1
    for a in list:
        name = 'number' + str(x)  -sharp 
        exec(name + '=a')  -sharp 
        exec('print(' + 'number' + str(x) + ')')
        x += 1

so, the first code prints the value of the 'number' + str (x) variable, and the second prints the value of the name variable

python~3.6/library/functions-sharpexec" rel=" nofollow noreferrer "> exec
Menu