我想知道是否有可能基于用户选择的值来获取全局变量名称。 例如,在游戏菜单中,如果用户选择值1,则显示“ START”(START是全局变量的名称)
我已经使用if-elif了,因为我的菜单不是很大,但是有没有更系统的方法?
print("The MENU")
print("Choose from the following:\n"
"1 - SEARCH A CONTACT\n"
"2 - ADD A CONTACT\n"
"3 - CHANGE A CONTACT\n"
"4 - DELETE A CONTACT\n"
"5 - DISPLAY CONTACTS\n"
"0 - Quit")
choice = int(input("Variant: "))
while choice not in [SEARCH_CONTACT, ADD_CONTACT, CHANGE_CONTACT, DELETE_CONTACT, DISPLAY_CONTACTS, QUIT]:
print("Not available, please select only from [0, 1, 2, 3, 4, 5]!")
choice = int(input("Your choice: "))
if choice == SEARCH_CONTACT:
print("You want to search a contact!")
elif choice == ADD_CONTACT:
print('You want to add a contact!')
elif choice == CHANGE_CONTACT:
print("You want to change a contact!")
elif choice == DELETE_CONTACT:
print('You want to delete a contact!')
elif choice == DISPLAY_CONTACTS:
print('You want to display the contacts!')
else:
print("QUITTING...")
除了一堆长长的代码,还有没有办法使用循环和仅一个print语句?全局变量的名称将更改为更精确的名称
答案 0 :(得分:0)
您不想直接这样做(Can I print original variable's name in Python?)
要做到要实现的目标的pythonic方法是使用字典(https://www.w3schools.com/python/python_dictionaries.asp)。
就是这样:
dictchoices = {
0: "NOTHING",
1: "SEARCH A CONTACT",
2: "ADD A CONTACT"
}
choice = int(input("Variant: "))
print("You want to ", dictchoice[choice], "!")
您还可以创建包含完整句子的另一本词典,以便仅从该词典中进行打印:
dictchoices2 = {
0: "You don't want to do anything. Too bad!",
1: "You want to search a contact. Be careful, contacts are scary.",
2: "You want to add a contact. Would that fill your existential void?"
}
choice = int(input("Variant: "))
print(dictchoice2[choice])