I am writing code to randomize exams, and I need to be able to randomize one variable so that it is chosen from a list but not equal to another variable.
I'm using eval() to evaluate a string and exec() to define the variables in python so that one value can be create from another. The issue I'm having is that in certain situations the variables aren't being recognized.
In situ, variable names and randomization parameters are pulled as text strings from a separate file. A simplified and extracted block of code that captures my problem is:
import random
def question_randomizer():
randomdef={'w':'random.choice([1,2,3])', 'x':'w+1', 'y':'random.choice([i for i in [w,x] if i not in [2]])', 'z':'random.choice([i for i in [1,2,3] if i not in [w]])'}
for var in randomdef:
variablevalue=eval(randomdef[var])
exec("%s = %s" % (var,variablevalue))
print(var, ' = ', variablevalue)
return
question_randomizer()
The exec call should define the variables within the code, and it works correctly in creating w, x, and y;
w = 2
x = 3
y = 3
but z always returns an error
name 'w' is not defined
Does anyone know how to fix this, or why this error is occurring when w has been used before successfully? My only additional caveat is that I am trying to avoid global variables.
Thanks.