0

i am trying to write code to set variable 'length' to the length of a list called the value of split[c], and have a random str from that list be printed.

Here's the code:

spit=input().split(' ')
c=0

#the bit i am having trouble with
def spitter():
    exec('length=len('+spit[c]+')-1')
    rand=random.randrange(0,length)
    exec('print('+spit[c]+'[rand])')

while not c==len(spit):
    spitter()
    c=c+1
  • 1
    Does this answer your question? [Variable not define after exec('variable = value')](https://stackoverflow.com/questions/35336702/variable-not-define-after-execvariable-value) – zr0gravity7 Jul 18 '21 at 21:26
  • but `len(spit[c])` will always be 1, so why are you using `exec()` inthe first place? – Max Shouman Jul 18 '21 at 21:28
  • also the `" "` inside `split()` is redundant – Max Shouman Jul 18 '21 at 21:28
  • 1
    Why are you asking the user for the name of a variable? Use a `dict` to map user input to the value you want to split. – chepner Jul 18 '21 at 21:37
  • yes, @chepner i am trying to ask the user for the name of the variable. i know i could use a dictionary but i am now curious as to why the code above doesn't work. – William Gosling Jul 19 '21 at 17:50
  • `exec` is ... tricky. Because the code generator doesn't know what `exec` is going to do, `length` is treated as a global variable here, but `exec` ends up defining a *local* variable. You could pass `globals()` as a second argument to `exec`, which would cause it to use the global scope as both the global *and* local scope for the code being executed. But it's better to just avoid using `exec` unless there is no alternative. – chepner Jul 19 '21 at 18:07

0 Answers0