0

I'm trying to make a simple control in Python 2 to make sure that the user's input is smaller than a given constant. If this is not the case it should ask again for another integer until it is smaller.

limit_store = 12

def input_store():
    sel_store = int(raw_input("Which store do you want? "))
    if sel_store > limit_store:
        print "Store number %i is not valid" % sel_store
        input_store()  
    return sel_store

store = input_store()

This worked the first time I wrote it in an Ipython notebook. Now if the first input is 9, it returns 9 as expected. If the input is 999, which is larger than 12, the if statement is runned and we get to select another integer. Selecting a correct input after a wrong one will return the old wrong input instead of the newer input.

1
  • You would need to return input_store(), the value of sel_store will be stored on the first call to the function so if you enter 100 different numbers you will always get the first unless you return Commented Apr 22, 2015 at 21:39

1 Answer 1

2

You need to save the value after printing the "invalid" message.

if sel_store > limit_store:
    print "Store number %i is not valid" % sel_store
    sel_store = input_store() # save value here

returning the number instead of saving it would also work - as long as the number goes somewhere useful instead of being thrown away. Python doesn't have TCO, so the performance benefit is minimal. The difference is in what you find preferable: that your function has a single return statement, or that it returns immediately instead of saving the variable first.

It would be simpler as a loop anyway:

def input_store():
    while True:
        sel_store = int(raw_input("Which store do you want? "))
        if sel_store <= limit_store: break
        print "Store number %i is not valid" % sel_store
    return sel_store
Sign up to request clarification or add additional context in comments.

7 Comments

or just return input_store()
So sorry. I forget to include that piece in the post. I'm editing now.
No - immediately after printing the "invalid" message, within the function.
I think it worked. I still not sure why my version doesn't work but I understand why your does. Thanks.
It's because you saved the initial attempt, but then the returned value of the recursive call wasn't saved, so in effect you had a line that was just a statement containing some number, which the interpreter immediately threw away.
|

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.