Python: Getch() not Recognized as a Defined Variable

588 views Asked by At

I'm new to python and am having trouble with the getch.getch command. I am creating a program that will print a binary numpy array that the user inputted - without hitting enter. To do this, I created an array of zeros and a list of letters with the coordinates that should be converted to ones, e.g.: a = ([x1, x2, x3],[y1, y2, y3]). I had the program working fine with a simple input() command. But when I switched to getch.getch, it prompted the following index error: "only integers, slicers ..." Is my program unable to recognize a getch input as a defined variable? What can I do to fix this problem? Thanks!

1

There are 1 answers

0
Kevin On BEST ANSWER

I'm guessing your code looks something like this:

a = (4,8,15)
b = (16,23,42)
c = (99, 100, 101)
value = input("choose a value:")
print value

And the result usually looks like this:

choose a value:b
(16, 23, 42)

And now you want to use getch instead of input. Am I on the right track?

in Python 2.7, getch and input work quite differently. input gets the user's input, evaluates it as if it were an expression, and returns the result. getch merely returns the character the user typed. This is why input gives you (4,8,15) and getch gives you "a".

Instead of storing each value as a separate variable, store all of them in a single dict, using their old variable names as keys. Then you can access the value if you know its name.

d = {
    "a": (4,8,15),
    "b": (16,23,42),
    "c": (99, 100, 101)
}
key = getch()
print d[key]