我有以下代码: https://repl.it/JRi4/2 其中我尝试在searchplayer()子函数中实现while循环
基本上,我需要检查字典播放器信息是否已满,然后继续搜索。如果它是空的(播放器信息中没有项目),则需要打印“添加玩家详细信息”并返回主菜单()
问题代码在这里:
def searchplayer():
print("===============SEARCH by player: Calculate average goals==================")
name = input("Player name : ")
if name in player_info.keys():
#print student_info
print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
else:
print("Please enter a valid player name:")
print()
mainmenu()
main()
我尝试过以下方法,但没有效果:
^{pr2}$错误
player_info not defined
此错误表明player_info未定义,但已声明为全局变量
假设您的}最初为空,则返回失败的解释:
player_info
确实是全局定义的,下面是一个循环代码,直到输入了player_info
字典中存在的名称,或者如果{更新。要删除递归,必须用一个无限循环来包装菜单(您要用
^{pr2}$sys.exit
退出,或者只使用break
退出,如果这是直接从main
调用的):现在,您可以简单地从选项处理函数中删除对
mainmenu()
的所有调用(最后一行是viewall
,update
,addplayers
和searchplayer
)。在如果您的代码执行
addplayers function first
,那么您的代码将完美地工作,因为这里声明了global
变量。如果您想先访问其他函数,它肯定会显示您和error
。所以最好先声明global
变量。我是说在main()
中,正如您的代码所描述的那样。在更新:如您的以下评论。在
正如您的第一个问题一样,}必须知道变量是
global
变量从任何子变量都能很好地工作,但是{global
声明的。在代码中的示例:当程序运行时,只需选择}。在
2
来执行searchplayer()
。它将按照您的指示运行并输入输入,当访问global player_info
时,它将显示一个错误。因为python
还没有得到任何{我再说一遍,}必须知道这个变量是{}。如果
global
变量可以从任何子变量访问,但是{python
知道变量是global
,那么你可以operate
在任何地方。这就是为什么我建议您在main
函数中将变量声明为global
。您可以在任何地方或任何函数声明它,但是首先执行函数,这就是python知道变量是global
的原因。我还提到了your code will work perfectly
,并解释了原因。在在尝试了整个代码之后,我建议您在这里将
SearchPlayer
切换为以下代码:还有一件事,您没有询问它,但是当您请求用户通过handling exceptions做出决策时,您应该为输入类型添加一个检查器,如下所示:
^{pr2}$当我输入字符串而不是int时,这有助于防止应用程序误崩溃
如果不想使用递归,可以执行以下操作:
和改变:
有:
(我选择从代码中去掉
sys.exit()
,因为它产生了一些警告)把你所有的方法都去掉{}。那应该很好
所以你的整个代码应该是这样的(我不熟悉更换对不起):
希望能帮上忙
相关问题 更多 >
编程相关推荐