我有一个包含字典的主函数。我还有另一个函数,我必须在主函数中访问字典才能使函数工作。我不知道我做错了什么。
def main():
# initial roster
brave_roster = {
"Austin Riley": "AB: 615, R: 90, H: 168, HR: 38, AVG: 0.273",
"Ronald Acuna": "AB: 467, R: 71, H: 124, HR: 15, AVG: 0.266",
}
# your code here
print("\t *** Braves Stats! ***\n")
print("Welcome to My Braves Stats! What can I do for you?\n")
print(' 1. Search for a player')
print(' 2. Add a new player')
print(' 3. Remove a player')
choice = int(input("Please type your choice number:"))
#player_look = input("Enter the name of the player you want to look up:")
#call functions
if __name__ == '__main__':
player_look = lookup_player(brave_roster)
main()
def lookup_player(brave_roster,choice):
player_look = input("Enter the name of the player you want to look up:")
if choice == 1:
print(player_look)
print(player_look,"Here are Austin's stats:",
brave_roster["Austin Riley"])
elif choice == 1:
print(player_look)
print("Here are Ronald's stats",
brave_roster["Ronald Acuna"])
else:
choice == False
print("N/A")
return brave_roster(player_look)
print("Thanks for using my Braves Stats.")
我尝试使用if __name__ == '__main__'
条件,但我的另一个函数未定义。
2条答案
按热度按时间gwo2fgha1#
Python是一种解释器语言,这意味着它逐行执行代码。
您的代码完全正确,但您调用此函数的位置不正确:
当Python到达
player_look = lookup_player(brave_roster)
时,lookup_player()
还没有定义。你会看到一个错误。另外,你在main函数内部使用了brave_rosterdictionary,所以它是main函数的属性,main函数不会与其他任何人共享它的属性,因为你需要在外部使用brave_rosterdictionary ...
要解决这个问题,请将整个条件移动到程序的末尾。
rxztt3cl2#
我会将用户输入保存在
main()
中,并将名称和选择都传递给lookup_player
。此外,您的return语句brave_roster(player_look)
需要使用方括号来访问dict值。在下面的情况下,您将调用brave_roster[name]
,但如果您想返回它,它必须在'else'中,我们知道名称在名册中:assert(name in brave_roster)
。否则,您将获得KeyError。