This snippet of code was supposed to generate a random number which represents a question. The number generator generates numbers from 1 through 10. But if the number is not in the list of numbers "numlist" it is supposed to generate another number. This is supposed to make it so that the program won’t ask the same question twice. using numlist.remove() did not work for this purpose. What will work? Or, what is a better method.
Also, I want to know how to make it so that there is less repetition in the code (loop?).
def roll():
var = random.randint(1,10)
if var not in numlist:
roll()
elif var == 1:
numlist.remove(1)
q1()
elif var == 2:
numlist.remove(2)
q2()
elif var == 3:
numlist.remove(3)
q3()
elif var == 4:
numlist.remove(4)
q4()
elif var == 5:
numlist.remove(5)
q5()
elif var ==6:
numlist.remove(6)
q6()
elif var == 7:
numlist.remove(7)
q7()
elif var == 8:
numlist.remove(8)
q8()
elif var == 9:
numlist.remove(9)
q9()
elif var == 10:
numlist.remove(10)
q10()
Keeping one function per question is not a good strategy. What if you want to change slightly how questions, hints and answers are given? You’re going to change dozens or even hundreds of functions?
A much better approach is an object-oriented one- for example, where each question is an object of the
Questionclass. For example:Any behavior that you originally encapsulated in the question function (limiting the number of guesses, limited amount of time, displaying in a certain format, whatever) would all be handled by methods of the
Questionclass. In the meantime, all the information specific to one question would be held in the data members (in this casequestion,hintsandanswers, although there could be other variables) that are specific to that question.You would create a question like this:
Or better yet, create them from a tab delimited file, where the file is something like:
And they are created like:
Then your main function would call methods of the
Question, which encapsulate its question-asking behavior. This would keep you from ever having to repeat code (all the code exists only in one place: the methods of theQuestionobject) and would keep all your questions in a flexible format.