我有以下程序和问题变量(字典)是player_info存储玩家信息(名称和目标)。为了解决目前出现的错误,我只需要将player_info设置为全局变量,但是我想知道是否stackoverflow专家可以建议或讨论解决此问题的替代方法的可能性不使用全局变量。具体示例:是否可以避免使用全局变量?
代码
#FOOTBALL COACH app
#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches
import sys
def main():
mainmenu()
def mainmenu():
print("=====WELCOME to the MAIN MENU=============")
print("""
1..........Add New Players & Goals
2..........Search by Players
3..........Quit
=========================================
""")
choice=int(input("Enter choice:"))
if choice==1:
addplayers()
elif choice==2:
searchplayer(player_info)
elif choice==3:
sys.exit()
else:
print("You must make a valid choice - 1, 2 or 3")
def addplayers():
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.
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:")
main()
如前所述,我知道,在addplayer()子重写,这将解决这个问题:
global player_info
player_info = {} #create a dictionary that stores the player name: player goals
...我期待找出解决问题的方法,而不使用全局变量。
更新:
一个答案下面使用回报player_info就是我想一起去的,但它并不相当,但工作。另外,每次添加播放器时,我都需要返回主菜单,不太确定如何操作,而且每次都没有mainmenu调用。有什么建议么? https://repl.it/JRl5/1
['return'](https://docs.python.org/3/reference/simple_stmts.html#grammar-token-return_stmt)字典 – DavidG