Search code examples
python-3.xuser-input

How to run different code per letter as you type in Python


I want to make my python code run a different function as you type, one function assigned per letter.

I would have the code for each letter

def a():
    # The letter A code
def b():
    # The letter B code

Then the input (something like this)

letters = input("Input Text:") 
print (letters)

And when it prints letters it runs the "a" function for a, "b" function for b, and so on. I'm pretty new to python so any help is appreciated.


Solution

  • Lets assume that all the functions for each letter is going to be a in a separate module called key_functions.py

    In the main program where you are going to process the letters:

    import key_functions
    def print(letter):
        for letter in letters:
             try:
                 key_func = getattr(key_functions, letter)
             except:
                 raise
             key_func()
    
    
    letters = input("Input Text:") 
    print(letters)
    

    NOTE: the print function is something which is going to be visible inside this module only!!