Quelklef
Quelklef

Reputation: 2147

Python 3 exec assignment error

I have this Python 3 code which is causing me issues:

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()

This should cause the prompt...

Just type a number in...

...And it does. And if I type in something other than a float, it gives the error...

Error! Try again!

...And re-prompts me. So far, so good. However, if I put in a normal number, it displays...

No Error

...When it should display variable customErrorMessage, in this case being...

-!- error message -!-

I originally thought that the issue was that in the exec() function, err wasn't being treated as a global variable, but using global err; err = 1 instead of just err = 1 doesn't fix it.

Upvotes: 2

Views: 335

Answers (1)

The6thSense
The6thSense

Reputation: 8335

To be straight forward:

your err value is never changed .It is always 0

using exec() doesn't change it

This changes will answer your question:

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()

cause of problem:

1.exec is a function in python3 so if you do any variable assignment in it it will not change the variable content it will only be available for the exec function

i.e)

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

For more on variable assignment you can see this both question so by martin and blaknight

edit:

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()

Upvotes: 1

Related Questions