【问题标题】:Python 3 exec assignment errorPython 3 exec 分配错误
【发布时间】:2015-07-31 05:31:17
【问题描述】:

我有这个导致我出现问题的 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 不会不要修复它。

【问题讨论】:

  • 请提供一个最小的例子。特别是,输入或其评估或循环都不应该是必需的。另请参阅stackoverflow.com/help/how-to-ask
  • 精简版...它显示了我在消除不必要代码的同时尝试做的基本想法。
  • 您的代码的问题在于,当您测试输入 variable = inputType(input(text)) 时,它实际上是将您输入的内容转换为 inputType。所以当你输入一个整数时,它会将数字转换为浮点类型。
  • @Digvijayad 这会导致什么问题?
  • 当用户输入一个整数时你想要一个错误,但是你的输入命令将输入​​转换为浮点数,因此没有错误。在此之后尝试打印变量。 variable = inputType(input(text))print(variable)。你会明白我的意思

标签: python python-3.x


【解决方案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()

【讨论】:

  • 我以为我在“我最初认为”部分解决了这个问题?
  • @Quelklef 你看到链接了吗
  • 你看到我的部分了吗?它应该可以工作,事实证明this code 有效
  • 另外:我是一个 Python 菜鸟,所以在理解您的链接时遇到了一些麻烦。
  • @Quelklef 研究过一会儿再说
猜你喜欢
  • 1970-01-01
  • 2011-12-21
  • 2018-12-02
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
  • 2013-02-10
  • 2021-02-08
  • 2015-11-09
相关资源
最近更新 更多