2017-07-07 43 views
0

我有以下代码: https://repl.it/JRi4/2 其中我试图在searchplayer()子实现while循环。while循环条件需要检查,如果字典包含项目,并返回到主菜单,如果不是

基本上,我需要检查字典player_info是否已满,然后才继续搜索。如果为空(在player_info没有物品),则需要打印的“添加播放器的详细信息”按钮,返回到MainMenu的()

有问题的代码是在这里:

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() 

我曾尝试以下,将无法正常工作:

def searchplayer(): 
    print("===============SEARCH by player: Calculate average goals==================") 
    name = input("Player name : ") 
    while player_info: 
    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() 
    print("Nothing in player_info") 
    mainmenu() 

main() 

错误

player_info not defined 

错误提示player_info没有定义,但它已被声明为一个全局变量

+3

“的错误提示player_info不在你链接的代码中定义的“=>不在任何地方定义。 “但它已被声明为全局变量”=>在哪里? –

+0

它是addplayer()中的一个全局变量,注意它在searchplayer()中的工作方式非常好......就我所知,问题与while循环的结构有关。我也需要它完成搜索后返回到主菜单,如果字典是空的 – MissComputing

+1

确实,我错过了它。请注意,直到调用addplayers()后才会定义WONT(并且每次调用addplayers()时都会覆盖它)。 –

回答

1

想你的整个代码后,我建议你在这里做的是切换你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做出决定如下:

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

它是有用的,以防止您的应用程序被误崩溃当我输入的字符串不是int。

,如果你不想使用递归,你可以这样做:

proceed = True 

def main(): 
    while proceed: 
     mainmenu() 

和改变:

sys.exit() 

有:

proceed = False 

(我只是选择了主动关闭sys.exit(),因为它产生了一些警告)

并为您的所有方法起飞mainmenu()。应该这样做很好

所以整个代码应该是这样的(我不熟悉repl.it不好意思):

#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() 

希望这有助于

+0

谢谢 - 但只是剪切和粘贴你的searchplayer(),它不起作用。 https://repl.it/JRi4/4 – MissComputing

+0

真的吗?它完全适用于我刚才给你的链接@MissComputing我编辑输出我得到 –

+0

https://repl.it/JRi4/5 ..它不会做问题的问题(但如此接近,谢谢) 。如果字典中没有任何内容并且将用户返回到主菜单,我需要它说“没有player_info”。如果字典中有某些东西,它应该继续询问玩家。问题的关键在于只询问玩家名称如果字典中有项目 – MissComputing

1

假设你player_info真的是全局定义的,这里的循环代码直到输入一个名称,它存在于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叫):

def mainmenu(): 
    while True: 
     choice = int(input("Enter choice:")) 
     if choice == 1: 
      addplayers() 
     elif choice == 2: 
      searchplayer() 
     elif choice == 3: 
      update() 
     elif choice == 4: 
      viewall() 
     elif choice == 5: 
      sys.exit() 
     else: 
      print("You must make a valid choice - 1, 2 or 3") 

现在,你可以简单地删除所有出现从选项处理函数(viewall,update,addplayerssearchplayer中的最后一行)呼叫mainmenu()

+0

会看看 - 但请看我的问题中的repl.it链接。 player_info是全局的addplayers() – MissComputing

+0

还有没有办法让它返回到主菜单,而不需要递归调用? – MissComputing

+0

我试过你的解决方案的searchplayer(),它不起作用。请注意,player_info在addplayer()中被定义为全局的,并且在while循环不存在的情况下,它在这个函数使用时可以很好地工作。 https://repl.it/JRi4/3 – MissComputing

1

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

更新:作为您的评论。

作为你的第一个问题global变量工作正常,但从python必须知道该变量被宣布为global

您的代码示例:当您的程序运行时,您只需执行2执行searchplayer()。它会按照您的指示运行并输入输入,当时间到达global player_info时,它将显示错误。由于python尚未得到任何global variable

=====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。如果python知道如何变量是global那么你可以operate它在任何地方。这就是为什么我建议你在main函数中声明变量为global。你可以在任何地方或任何函数声明它,但首先执行这个函数,这就是为什么python知道变量是global。我也提到your code will work perfectly并解释它为什么。

+0

是不是在整个程序中的全局变量中声明的全局变量?你是否建议它需要在main()中声明?这不可能是正确的,因为它在searchplayer()中工作正常,但没有声明它是主要的。这只是我添加的while循环,似乎会歪曲事情并导致此错误 – MissComputing

+0

@MissComputing请检查我的更新回答,以获得您的评论问题。希望这会有所帮助。 –

+0

谢谢 - 但如果你只是在全部变量之外没有关键词“global”声明全局变量,它也可以工作吗? – MissComputing

相关问题