0

I want to know if it is possible to get the global variable name based on a value chosen by the user. For example in a game Menu, if the user chooses value 1, then to display "START" (START being the global variable's name)

I already did it with if-elif, as my Menu is not very large, but is there a more systematic approach?

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...")

Instead of this long bunch of code, is there a way to use a loop and just one print statement? The global variables' names will be changed with more precise ones

1 Answers1

0

You wouldn't want to do that directly (Can I print original variable's name in Python?)

The pythonic way to do what you want to achieve would be to use a dictionary (https://www.w3schools.com/python/python_dictionaries.asp).

Namely something like that:

dictchoices =   {
0: "NOTHING",
1: "SEARCH A CONTACT",
2: "ADD A CONTACT"
}

choice = int(input("Variant: "))

print("You want to ", dictchoice[choice], "!")

You can also create another dictionary with complete sentences so that you only print from that dictionary :

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])
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
AdrienNK
  • 850
  • 8
  • 19