1

So this is my code:

if spot == 4:
        exec("ch" + str(spot) + " = " + "vl" + str(spot) )
        displayword.append(ch4)
    else:
        exec("ch" + str(spot) + " = " + "'_'")
        displayword.append( ("ch"+str(spot) ))

My output on the word orange would be:

Orange ['ch0', 'ch1', 'ch2', 'ch3', ' g ', 'ch5']

So when I use displayword.append(ch4), I get the value of ch4 but when I just "ch" + str(spot) I simply get that value as a string value.. I tried exec (("ch"+str(spot) ) ), but I just got None as the values in the list..

10 Rep
  • 2,217
  • 7
  • 19
  • 33
jasonmzx
  • 507
  • 5
  • 15
  • 3
    a better approach would be to use dictionaries, e.g. `d = {"spot": "value_of_spot"}` – Chris_Rands Jun 29 '20 at 16:15
  • 1
    Anytime you find yourself using `exec`, your first thought should be either "What did I do wrong?" or "How can I avoid using `exec`?" – chepner Jun 29 '20 at 16:21

1 Answers1

2

Don't use lots of similarly named variables; use a dict for both ch and vl.

if spot == 4:
    ch["4"] = vl["4"]
else:
    ch[spot] = '_'

# Or
# ch[spot] = vl["4"] if spot == 4 else '_'

displayword.append(ch[spot])
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Hey, thanks for the answer, however how can I assign letters to the vl variable based of dictionaries? because I used: exec("vl" + str(spot) + " = " + " ' " + x_vc + " ' ") to assign 1 variable to each letter – jasonmzx Jun 29 '20 at 17:55
  • `vl[spot] = x_vc`? – chepner Jun 29 '20 at 17:58
  • Yep got it, my issue was I was defining my dicts and lists and thats why the vl[spot] = x_vc line wasnt workin, thanks for all your help chep! – jasonmzx Jun 29 '20 at 18:13