简体   繁体   English

重复python函数并返回值

[英]Repeat python function and return value

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? 为什么会这样?

你需要在函数的尾部return test() ,以返回有效调用test()返回的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM