[英]Python: None value when returning from function
我正在编写一个程序,将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)
例如,这些是输入和输出:
What name do you want for your player?
p1
input score?
3
What name do you want for your player?
p2
input score?
6
Your attack score must be between 0 and 5
input score?
5
What name do you want for your player?
p3
input score?
2
p1 3
p2 None
p3 2
我觉得我很想念一些东西。 谁能指出我正确的方向?
您在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)
输出:
What name do you want for your player?
shovon
input score?
2
2
What name do you want for your player?
sorida
input score?
23
Your attack score must be between 0 and 5
input score?
43
Your attack score must be between 0 and 5
input score?
234
Your attack score must be between 0 and 5
input score?
1
1
What name do you want for your player?
shody
input score?
2
2
shovon 2
sorida 1
shody 2
根据官方文件 :
实际上,即使没有return语句的函数也确实会返回一个值,尽管这很无聊。 此值称为“无”(这是一个内置名称)。
执行此操作时:
if int(score)>5:
playerscore()
您调用playerscore
函数而无需return
语句。 这将产生None
值。
您尝试对代码进行的递归类型将对您的代码进行一些小的更正...如下:
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异常:
def playerscore():
global teamtotal
score=input("input score?\n")
try:
while int(score) < 0 or int(score) > 5:
print("Your attack score must be between 0 and 5")
print(score) # check
score = input("input score?\n")
except ValueError:
print("Your attack score must be A NUMBER between 0 and 5")
return playerscore()
return int(score)
希望对您有所帮助。 问候。
当函数不返回任何值时,值将为None
。
因此,对于score
大于5的情况,您应该检查代码。(与分数不大于5的情况进行比较)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.