简体   繁体   English

函数返回无

[英]Function returns None

After making an error then doing recursion i get None.在犯错误然后进行递归后,我得到了 None。

def getplayerinput():
    a = ["rock","paper","scissors"]
    plin = raw_input("Choose %s/%s/%s: " %(a[0], a[1], a[2]))
    print plin,'-first print'
    if plin not in a:
        print "Wrong input"
        getplayerinput()
    else:
        print plin,'-second print'
        return plin

for i in range(0,11):
    print getplayerinput()

If you input first 'rock' then 'cat' then 'paper' you will get a 'None'.如果您先输入“rock”,然后输入“cat”,然后输入“paper”,您将得到“None”。

You do not return anything once the input is not valid.一旦输入无效,您就不会返回任何内容。 Do this instead:改为这样做:

def getplayerinput():
    a = ["rock","paper","scissors"]
    plin = raw_input("Choose %s/%s/%s: " %(a[0], a[1], a[2]))
    print plin,'-first print'
    if plin not in a:
        print "Wrong input"
        return getplayerinput() # <- added return
    else:
        print plin,'-second print'
        return plin

for i in range(0,11):
    print getplayerinput()

Otherwise the recursion call will return something to a top level call, but that one just swallows the return value from the recursion call, since it doesn't pass it on via return.否则递归调用将返回一些东西给顶级调用,但那个只是吞下了递归调用的返回值,因为它没有通过返回传递它。

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

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