2017-07-07 44 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

相關問題