Search code examples
pythonrandomimportuser-input

python: import random for multiple question


I have already created a login(). Trying to ask a random question each time and if answered correctly to run login().

Below is the outline of what I am trying to do:

>>> def human_check():
question1 == raw_input('1+1=')#question.1#
while question1 !== '2':
    print 'sorry robot , try again'
else:
    return login()
question2 == raw_input('the cow jumped over the ....')#question.2#
while question2 !== '2':
    print 'sorry robot , try again'
else:
    return login()
import random
random.question

I imported the random module but how do I group the questions so that random. will work?

SyntaxError: invalid syntax
>>> 

Solution

  • You can do something like this:

    import random
    
    questions = []
    questions.append(("1+1=", "2"))
    questions.append(("the cow jumped over the ....", "moon"))
    
    def human_check():
        random_question = random.choice(questions)
        question, answer = random_question
        user_answer = raw_input(question)
        if user_answer != answer:
           print "Sorry, try again."
        else:
           return login()
    

    Basically, if you maintain some list of questions, you can use random.choice to make a random selection from that list.