<p>可以在函数中使用<code>return</code>,以避免使用全局变量。下面是一个简单的例子:</p>
<pre><code>def addplayers():
player_info= {}
name = input("Enter Name: ")
test = int(input("Enter a number: "))
player_info[name] = test
return player_info
player_info = addplayers()
</code></pre>
<p>如果您想在另一个函数中使用它,只需将字典作为参数传递给该函数:</p>
<pre><code>def searchplayers(player_info):
print (player_info)
</code></pre>
<p>注:关于“<a href="https://stackoverflow.com/questions/19158339/why-are-global-variables-evil">Why are global variables evil?</a>”的有趣答案</p>
<p>编辑:</p>
<p>您的<code>addplayers()</code>正在调用<code>mainmenu()</code>,而它本身正在<code>mainmenu()</code>内调用。这是一个递归函数,除非有充分的理由,否则最好避免使用这些函数。我将把<code>mainmenu</code>的内容放在<code>while</code>循环中,直到满足某个条件。完整的代码如下所示(我删除了<code>main</code>函数,因为它实际上什么都没做):</p>
<pre><code>def mainmenu():
stop = False
while stop == False:
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:
player_info = addplayers()
elif choice==2:
searchplayer(player_info)
elif choice==3:
print ("Exit the main menu")
stop = True
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.
return player_info
def searchplayer(player_info):
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:")
mainmenu()
</code></pre>