2017-07-30 125 views
0

我從CSV文件讀取並創建一個函數,將玩家與該文件分隔爲2個列表:經驗豐富的玩家和新玩家。新函數不接受來自其他函數的返回值

然後,我試着創建另一個函數來打印每個列表的長度。但是,當我運行腳本並調用2個函數時,Python返回一個錯誤,指出第二個函數的變量未定義。不知道我做錯了什麼。

import csv 

with open('soccer_players.csv', newline='') as csvfile: 
    players_reader = csv.DictReader(csvfile, delimiter=',') 
    players = list(players_reader) 

def separate(players): 
    experienced = [] 
    fresh = [] 
    for player in players: 
     if player['Soccer Experience'] == 'YES': 
      experienced.append(player) 
     else: 
      fresh.append(player) 

    return experienced, fresh 


def countexperience (experienced, fresh): 
    players_experience = len(experienced) 
    players_fresh = len(fresh) 

    print(players_experience) 
    print(players_fresh) 

while True: 
    start = input("Want to start? (Y/n) ").lower() 
    if start == "y": 
     separate(players) 
     countexperience(experienced, fresh) 
     break 
    elif start == "n": 
     print("goodbye") 
     break 
    else: 
     print("letter not accepted! Please write 'Y' to start or 'N' to exit!\n") 

結果:

countexperience(experienced, fresh) 
NameError: name 'experienced' is not defined 

回答

0

separate()局部變量不會添加到當前的範圍,所以你需要分配的separate()變量在當前範圍內的回報,如:

experienced, fresh = separate(players) 

注意:您可以使用任何你想要的名字,例如

e, f = separate(players) 
countexperience(e, f) 

您也可以擴大從separate()直接在函數調用countexperience()tuple回用*,例如:

countexperience(*separate(players)) 
相關問題