while循环条件需要检查字典是否包含项目,如果有则返回主菜单

2024-10-02 10:27:32 发布

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

我有以下代码: 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未定义,但已声明为全局变量


Tags: 代码namehttpsinfo信息错误itrepl
3条回答

假设您的player_info确实是全局定义的,下面是一个循环代码,直到输入了player_info字典中存在的名称,或者如果{}最初为空,则返回失败的解释:

def searchplayer():  
   print("===============SEARCH by player: Calculate average goals==================")
   while len(player_info) > 0:
       print("Please enter a valid player name:")
       name = input("Player name : ")
       if name in player_info.keys():
           print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
           break
   else:
       print("No players found. Please add some first.")
   print()
   mainmenu()

更新。要删除递归,必须用一个无限循环来包装菜单(您要用sys.exit退出,或者只使用break退出,如果这是直接从main调用的):

^{pr2}$

现在,您可以简单地从选项处理函数中删除对mainmenu()的所有调用(最后一行是viewallupdateaddplayerssearchplayer)。在

如果您的代码执行addplayers function first,那么您的代码将完美地工作,因为这里声明了global变量。如果您想先访问其他函数,它肯定会显示您和error。所以最好先声明global变量。我是说在main()中,正如您的代码所描述的那样。在

更新:如您的以下评论。在

正如您的第一个问题一样,global变量从任何子变量都能很好地工作,但是{}必须知道变量是global声明的。在

代码中的示例:当程序运行时,只需选择2来执行searchplayer()。它将按照您的指示运行并输入输入,当访问global player_info时,它将显示一个错误。因为python还没有得到任何{}。在

=====WELCOME to the MAIN MENU=============
1..........Add New Players & Goals
2..........Search by Players (return average goals)
3     Update Player Goals
4     View All players
5..........Quit

=========================================

Enter choice: 2
===============SEARCH by player: Calculate average goals==================
Player name :  messi
Traceback (most recent call last):
  File "python", line 91, in <module>
  File "python", line 11, in main
  File "python", line 30, in mainmenu
  File "python", line 83, in searchplayer
NameError: name 'player_info' is not defined

我再说一遍,global变量可以从任何子变量访问,但是{}必须知道这个变量是{}。如果python知道变量是global,那么你可以operate在任何地方。这就是为什么我建议您在main函数中将变量声明为global。您可以在任何地方或任何函数声明它,但是首先执行函数,这就是python知道变量是global的原因。我还提到了your code will work perfectly,并解释了原因。在

在尝试了整个代码之后,我建议您在这里将SearchPlayer切换为以下代码:

def searchplayer():  
    print("===============SEARCH by player: Calculate average goals==================")

    if len(player_info.keys())==0:
        print("you have no players registered")
    else:
        name = input("Player name : ")
        while name not in player_info.keys():
            print("Please enter a valid player name:")
            name = input("Player name: ")
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))

    print()
    mainmenu()

还有一件事,您没有询问它,但是当您请求用户通过handling exceptions做出决策时,您应该为输入类型添加一个检查器,如下所示:

^{pr2}$

当我输入字符串而不是int时,这有助于防止应用程序误崩溃

如果不想使用递归,可以执行以下操作:

proceed = True

def main():
    while proceed:
        mainmenu()

和改变:

sys.exit()

有:

proceed = False

(我选择从代码中去掉sys.exit(),因为它产生了一些警告)

把你所有的方法都去掉{}。那应该很好

所以你的整个代码应该是这样的(我不熟悉更换对不起):

#SOLUTION==================FOOTBALL COACH app

#The program allows a user to enter a number of students (their names and test 
#scores) and then search for a student, returning their average score for the 
#three tests

#1   Create a similar program for a football coach (he wants to store player 
#names + goals for 3 matches)
#2   -main menu that allows for 1. Adding players + goals and 2. Search by 
#Player 3. Quit
#3  -When complete, go back and add additional menu options for "View all     
#players" and Update". This allows the coach to update the number of goals for     
#any given player as well as view all

import sys #note the sys.exit() command will not work without this

player_info={}
proceed = True

def main():
    while proceed:
       mainmenu()


def mainmenu():
    global proceed
    print("=====WELCOME to the MAIN MENU=============")
    print("""
  1..........Add New Players & Goals
  2..........Search by Players (return average goals)
  3     Update Player Goals
  4     View All players
  5..........Quit

  =========================================
  """)
    try:
        choice=int(input("Enter choice:"))
    except:
        print("Input must be int from 1-5")
        mainmenu()

    if choice==1:
        playerinfo=addplayers()
    elif choice==2:
        searchplayer()
    elif choice==3:
        update()
    elif choice==4:
        viewall()
    elif choice==5:
        proceed = False
    else:
        print("You must make a valid choice - 1, 2 or 3")


def viewall():

    for keys, values in player_info.items():
        print(keys, values)
    print()

def update():
    playername=input("Which player's goals do you wish to update?:")
    m1=int(input("Match 1 new entry:"))
    m2=int(input("Match 2 new entry:"))
    m3=int(input("Match 3 new entry:"))
    if playername in player_info:
        #myDict["A"] = "Application"
        player_info[playername]="Boo"
        player_info[playername]={"Match 1 goals":m1,"Match 2 goals":m2,"Match 3 goals":m3}


def addplayers():
    global player_info #this needs to be declared as a global variable so it can be used by searchplayer()
    player_info= {} #create a dictionary that stores the player name: player goals
    num_players = int(input("Please enter number of players you wish to enter:"))
    print ("You are entering %s players" %num_players)
    player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
    for i in range(0,num_players):
        player_name = input("Enter Player Name :")
        player_info[player_name] = {}
        for entry in player_data:
            player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
        print()





def searchplayer():  
    print("===============SEARCH by player: Calculate average goals==================")
    if not player_info:
        print("you have no players registered")
    else:
        name = input("Player name : ")
        while name not in player_info.keys():
            print("Please enter a valid player name:")
            name = input("Player name: ")
        #print student_info
        print ("Average player goals : ", str(sum(player_info[name].values())/3.0))

    print()

main()

希望能帮上忙

相关问题 更多 >

    热门问题