I simply cannot understand what is happening here. The problem is important for my homework (studying programming so I’m a beginner… also my English is not that good, sorry).
I am trying to read a string… it can be either a number or a set number of commands.
I’ll just give a very small example of what I’m trying to do and what is going wrong.
def validate():
choice = str(input(">>> "))
if (choice == "exit"):
return 0 # should exit validate
else:
try:
aux = int(choice) # Tries converting to integer
except:
print("Insert integer or exit")
validate() # If it can't convert, prompts me to try again through
# recursivity
else:
return aux
rezult = validate()
print (rezult)
Problem is that this small script returns totally random stuff.
If “exit”, returns “None”.
If first input is correct, it returns correct number.
If first input is an “error” and second input is correct, it’s “None” again and I simply can’t understand what is going wrong… Why it doesn’t want to work or what should I do (alternatively).
In case you enter the
exceptblock, the functionvalidate()uses a recursive call to call itself. When this call returns, it returns to the place where the function was called, i.e. into theexceptblock. The return value ofvalidate()is ignored at this point, and control reaches the end of the outer call without hitting areturnstatement, soNoneis implicitly returned.Don’t use recursion here. Use a loop.