Python 3 exec赋值错误

时间:2015-07-31 05:31:17

标签: python python-3.x

我有这个Python 3代码导致了我的问题:

def setStartingVariable(inputType, text, code = None, customErrorMessage = "Error: No error message"):
    while True:
        try:
            variable = inputType(input(text)) # Test if the inputted variable is of the right type. Keep in mind inputType is a variable, not a function.
        except BaseException: 
            print("Error! Try again!")
            continue
        err = 0 # Reset
        if code != None:
            exec(code)
        if err == 0:
            print("No error")
            return variable
        elif err == 1:
            print(customErrorMessage)
        else:
            print("Error: var err != 1 and != 0")


def inputStartingVariables():
    global wallet
    wallet = setStartingVariable(float, "Just type a number in... ", "err = 1", "-!- error message -!-")

inputStartingVariables()

这会导致提示......

Just type a number in...

......确实如此。如果我输入浮动以外的东西,它会给出错误...

Error! Try again!

......然后重新提示我。到现在为止还挺好。但是,如果我输入正常数字,它会显示......

No Error

...当它显示变量customErrorMessage时,在这种情况下是......

-!- error message -!-

我原本认为问题是exec()函数中err未被视为全局变量,而是使用global err; err = 1代替只有err = 1并没有解决它。

1 个答案:

答案 0 :(得分:1)

要直截了当:

your err value is never changed .It is always 0

使用exec()无法更改

此更改将回答您的问题:

def setStartingVariable(inputType, text, code = None, customErrorMessage = "Error: No error message"):
    while True:
        try:
            variable = inputType(input(text)) # Test if the inputted variable is of the right type. Keep in mind inputType is a variable, not a function.
        except BaseException: 
            print("Error! Try again!")
            continue
        exec_scope = {"err" :0}
         # Reset
        if code != None:
            print ("here")
            exec(code,exec_scope)

        print (code)
        if exec_scope["err"] == 0:
            print("No error")
            return variable
        elif exec_scope["err"] == 1:
            print(customErrorMessage)
        else:
            print("Error: var err != 1 and != 0")


def inputStartingVariables():
    global wallet
    wallet = setStartingVariable(float, "Just type a number in... ", "err = 1", "-!- error message -!-")
inputStartingVariables()

问题原因:

1.exec是python3中的一个函数,所以如果你在其中做任何变量赋值,它将不会改变它只能用于exec函数的变量内容

<强>即)

def a():
    exec("s=1")
    print (s)
a()

Traceback (most recent call last):
File "python", line 4, in <module>
File "python", line 3, in a
NameError: name 's' is not defined

有关变量分配的详情,您可以通过martinblaknight

看到这两个问题

修改

def setStartingVariable(inputType, text, code = None, customErrorMessage = "Error: No error message"):
    global err
    while True:
        try:
            variable = inputType(input(text)) # Test if the inputted variable is of the right type. Keep in mind inputType is a variable, not a function.
        except BaseException: 
            print("Error! Try again!")
            continue

        err = 0 # Reset
        if code != None:
            exec("global err;"+code)
            print (err)
        if err == 0:
            print("No error")
            return variable
        elif err == 1:
            print(customErrorMessage)
        else:
            print("Error: var err != 1 and != 0")


def inputStartingVariables():
    global wallet
    wallet = setStartingVariable(float, "Just type a number in... ", "err = 1", "-!- error message -!-")

inputStartingVariables()