-1

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!

  • Which version of Python are you using? – Kevin Nov 17 '14 at 17:22
  • 1
    possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – Kevin Nov 17 '14 at 17:25
  • I'm using python 2.7.8. I followed your answer (and also reviewed dictionaries) - thank you - but am receiving a syntax error. My dictionary looks like: d = {"a": ([2,5,8],[0,0,0]), "b": ([3,5,7],[0,2,4]), "c": ([1,2,3],[2,4,6])}. Do you see an error? Thanks again. – Mark Sperling Nov 18 '14 at 02:03
  • There aren't any syntax errors in that dictionary. Try looking at the line above that line. Sometimes Python is off by one when it tells you what line the problem is on. It's usually a missing right parentheses. – Kevin Nov 18 '14 at 12:50

1 Answers1

1

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]
Kevin
  • 74,910
  • 12
  • 133
  • 166