Search code examples
pythonfunctiondictionarycall

Can I call a function by inputting a string?


I want to make a function that can be called when the text input is equal to a command.

from os import system
from time import sleep
import ctypes

ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat')

print('Hi, welcome to my basic chat engine!')

sleep(5)

system('cls')

username = input('Enter a username: ')

ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat - ' + username)

system('cls')

def commands (command):
    commandlist = ['/help','/clear', '/commands']
    commanddict = {'/help' : 'help', '/clear' : 'clear', '/commands' : 'commands'}
    for possibility in commandlist:
        if command == possibilty:
            commanddict[possibility]()
            break 

def textInput (text):
    if text[0] == '/':
        commands(text)

Does line 24 work to call a function? The way I am imagining it will work is that it will find the entry for the key 'possibility', and then call that as a function, but I am not sure.

If the previous code does not work, what would?


Solution

  • Suppose there's a function called help, clear,... in your code like this.

    def help():
        print("help!")
    

    Then, the below commands function will do what you want. Note that function can be used as value of dictionary in Python.

    def commands (command):
        command_dict = {'/help' : help, '/clear' : clear, '/commands' : commands}
        func = command_dict.get(command)
    
        if func is not None:
            func()
        else:
            print("I don't have such a command: %s" % command)
    

    I guess '/commands''s value(command function) in command_dict should be changed to another function. The program will crash if you type 'commands'.