0

I have a problem in many of my scripts, this is a stripped down version if the problem code:

list1 = ["item1","item2"]
def test():
    if 1 == 1:
        var1 = input ("var1? ")
        if var1 not in list1:
            print("please enter existing item")
            test()
    print(var1)

test()     

It gives weird outputs like

var1? 23 please enter existing item var1? 4 please enter existing item var1? 23 please enter existing item var1? 2 please enter existing item var1? item1 item1 2 23

23

Why does it not just overwrite var1? How can I work around this in a script? Keep in mind that I need to use var 1 down the same function (and other places) elsewhere, so I do need to assign it to a variable.

RnRoger
  • 682
  • 1
  • 9
  • 33
  • 1
    Because you are calling `test()` *again*, and each invocation has their *own* local variables. Don't use recursion to handle user input, see [Asking the user for input until they give a valid response](//stackoverflow.com/q/23294658) – Martijn Pieters Dec 17 '16 at 18:02
  • it's because you're using recursion, rather than a loop. In the first function, var1 is set to 23, and then you call a new copy of `test()`... as soon as `var1` is in `list1`, new copies of `test()` are not called, and so it works its way back up through all the copies of `test()` and prints out all of the different versions of `var1` – Simon Fraser Dec 17 '16 at 18:03
  • The idea of a call stack -- with distinct arguments and locals for each entry in that stack -- is a critical one to understand; languages/runtimes without a comparable facility are *extremely* rare. – Charles Duffy Dec 17 '16 at 18:06

0 Answers0