Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat python function and return value

Tags:

python

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?

like image 559
user1739613 Avatar asked Dec 16 '22 18:12

user1739613


2 Answers

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

like image 190
Mike Corcoran Avatar answered Jan 05 '23 01:01

Mike Corcoran


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
like image 36
John La Rooy Avatar answered Jan 04 '23 23:01

John La Rooy