2

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.

8
  • Please provide a minimal example. In particular, either the input or its evaluation or the loop shouldn't be necessary. See also stackoverflow.com/help/how-to-ask. Commented Jul 31, 2015 at 5:35
  • This is the stripped-down version... It shows the basic idea of what I'm trying to do while eliminating the unecessary code. Commented Jul 31, 2015 at 5:39
  • The problem with your code is that when you are testing for input variable = inputType(input(text)) , it is actually converting what ever you input to the inputType. So when you type a integer, it converts the number to type float. Commented Jul 31, 2015 at 6:07
  • @Digvijayad How does that cause an issue? Commented Jul 31, 2015 at 6:17
  • You want an error when the user inputs a integer, but your input command converts the input to float, hence no error. try printing the variable after this. variable = inputType(input(text)) print(variable). You will see what i mean Commented Jul 31, 2015 at 6:20

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

8 Comments

I thought I addressed this issue under my "I originally thought" section?
@Quelklef did you see the links
Did you see my section? It should work, as proven by the fact that this code works
Also: I'm a bit of a Python noob, so I'm having some troubles understanding your links.
@Quelklef researching will say in a moment or so
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.