Python:从函数返回时没有值

2024-05-14 00:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个程序,把3个球员和他们的分数存储在一个列表中,然后在最后打印出来。其实很简单,但是我尝试从一个名为playerscore()的函数中调用玩家分数的值,该函数阻止您输入分数>5。在

当您使用正确的值运行它时,它可以正常工作,但是如果您输入了一个不正确的值>;5,那么它将再次启动playerscore函数,并允许输入新值,但返回“None”

teamlist = []

def playercreator():
    counter=0
    while counter < 3:
        name = playername()
        score = playerscore()
        print(score) #check - this one goes wrong when returned after the if/else in playerscore()
        teamlist.append(name+" "+str(score))
        counter = counter + 1

def playername():
    name=input("What name do you want for your player?\n")
    return (name)

def playerscore():
    global teamtotal
    score=input("input score?\n")
    print(score) #check
    if int(score)>5:
        print("Your attack score must be between 0 and 5")
        print(score) #check
        playerscore()
    else:
        return int(score)

playercreator()

for x in teamlist:
    print(x)

例如,这些是输入和输出:

^{pr2}$

我觉得有什么明显的东西我错过了。谁能给我指出正确的方向吗?在


Tags: 函数nameinputifdefcheckcounterelse
3条回答

执行此操作时:

if int(score)>5:
    playerscore()

调用playerscore函数时没有return语句。这将产生None值。在

if块中缺少return语句(分数大于5时):

def playerscore():
    global teamtotal
    score=input("input score?\n")
    if int(score)>5:
        print("Your attack score must be between 0 and 5")        
        return playerscore()
    else:
        return int(score)

输出:

^{pr2}$

来自official documentation

In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name).

你试图对你的代码进行的递归类型只需对你的代码做一点小小的修正。。。具体如下:

def playerscore():
global teamtotal
score=input("input score?\n")
print(score) #check
if int(score)>5:
    print("Your attack score must be between 0 and 5")
    print(score) #check
    return playerscore()
else:
    return int(score)

您可以注意到,这次我们返回了playerscore()。由于您似乎正在学习基础知识,我想提出一种稍微不同的方法,因为如果播放器键入的是字符串(一些字母)而不是数字,则会出现ValueError异常。您可以在异常捕获中继续使用递归函数,并使用while循环使播放器将数字保持在所需的范围内。以下是我的建议,以防止ValueError异常:

^{pr2}$

我希望这有帮助。当做。在

相关问题 更多 >