4

I am trying to have a function repeat itself if a certain criteria is not met. For instance:

def test():
    print "Hello",
    x = raw_input()
    if x in '0123456789':
        return x
    test()

In this program if you type a number the first time, it will return the number. If you type some non-number, it will repeat itself as desired. However, if you type some non-numbers and then a number, it will return nothing. Why is that the case?

3
  • 2
    It should work if you replace test() with return test(). Commented Oct 11, 2012 at 22:43
  • 1
    If you want to repeat a prompt until you get valid input I'd suggest using a while loop rather than recursion. Every time the input is invalid you get another frame pushed on the stack. Probably not a big deal for what you're doing, but no harm in being tidy. Commented Oct 11, 2012 at 22:47
  • @cjm, if what you're doing is "learning to program" it is a big deal. But mistakes can be a good thing if you learn from them. Commented Oct 11, 2012 at 23:28

2 Answers 2

8

you need to return test() at the tail of the function to return the value that the valid call into test() returns.

Sign up to request clarification or add additional context in comments.

Comments

4

The way you are having test call itself is the wrong way to do it. Each time your program restarts the function, you will use up another level of stack. Eventually the program will stop(crash) even if the user never inputs one of those characters.

def test():
    while True:
        print "Hello",
        x = raw_input()
        if x in '0123456789':
            return x

1 Comment

You know you are right, and you know the code you posted is simply not fun. :-) But, the code will work the way the o.p. envisioned - for this purpose - @mikecorcoran's answer has the real problem nailed.

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.