简体   繁体   中英

Python: How to use a dictionary to call methods (values in dictionary) to run based on user input (key in dictionary) in a different function?

What I have so far:

def run_A():
   # code...

def run_B():
   # code...

def run_C():
   # code...

inputDict = {'a': run_A, 'b': run_B, 'c': run_C, 'q': False}  # q for quit program
def userChoice(self):
    y = True
    while y:
       choice = input("a. run A\nb. run B\nc. run C\nq. Quit").lower()
       self.inputDict[choice]

My issue here is that the program allows the user to input their choice, but the function will be called based on dictionary (won't run) and program will only keep asking user for their choice.

self.inputDict[choice]只会从 dict 获取函数,不会调用它,所以也许你需要用self.inputDict[choice]()替换self.inputDict[choice]

def run_A():
    print("A")
   # code...

def run_B():
    print("B")
   # code...

def run_C():
    print("C")
   # code...

inputDict = {'a': run_A, 'b': run_B, 'c': run_C, 'q': False}  # q for quit program
def userChoice(self):
    y = True
    while y:
       choice = input("a. run A\nb. run B\nc. run C\nq. Quit").lower()
       if choice =="q":
           y = False
       else:
           self.inputDict[choice]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM