0

How can I pipe the variable name dynamically? My point is, if user's input is 'c', then counterc should raise with 1.

Here is what I have so far.

counterc = 0
countern = 0
counterx = 0
letter = input()

if letter in ['c','n','x']:
  counter${letter} += 1 # does not work
  eval('counter' + letter + '=' + 1) # tried with this one too, but still does not work
Yavorov
  • 3
  • 1
  • 2
    What are the counters supposed to do? why not just have a `counter` dict` that you can increment each key in? – Sayse Oct 15 '19 at 11:46

3 Answers3

1
counterc = 0
countern = 0
counterx = 0
letter = input()

if letter in ['c','n','x']:
    globals()['counter{}'.format(letter)] += 1
    print(globals()['counter{}'.format(letter)])

Thank me later if you are using python2 input 'c' of you are on py3 just type c without quotes.

Karandeepdps
  • 314
  • 1
  • 10
1

the eval method is used to return a value, not for executing string command and only accept one line command

To execute string command, you need the exec method, here is the correct code

counterc = 0
countern = 0
counterx = 0
letter = input()

if letter in ['c','n','x']:
  exec('counter' + letter + '=' + 1)
0

the locals built-in function provides a (variable_name => variable_value) dictionary of the locals variables. Moreover, this dictionary is not read-only.
Then locals()[f"counter{letter}"] += 1 should do the job.
If you are using an older python version than 3.6 use locals()[f"counter{}".format(letter)] += 1 instead.

SPH
  • 478
  • 2
  • 6
  • "SyntaxError: invalid syntax" when I try this – Yavorov Oct 15 '19 at 11:54
  • Try "counter{}".format(letter) instead: f-strings came in python 3.6, maybe you have an older version ? – SPH Oct 15 '19 at 11:56
  • `locals` is a function that returns a reference to the local dictionary. You should do `locals()[...]` instead. – SyntaxVoid Oct 15 '19 at 12:03
  • Additionally, the use of `locals` will **fail** (no change happens) if used within the scope of a function. Try `def f(): x=3; locals()["x"] = 4; print(x)`. It prints `3` instead of `4`. **`locals()` is read-only in function scopes.** – SyntaxVoid Oct 15 '19 at 12:05