i want to make sure that people can quit in the middle of the game and the question is random not in order... please help me..

# make input equal to Python3 style input even in Python2
import random


try:
    input = raw_input
except:
    pass
question =" "
print("Welcome to my yes or no quiz!")



questions = (("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    ("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
    ("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
    ("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
    ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
    ("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
    ("The All Blacks are New Zealands top rugby team ", 'yes'),
    ("The Treaty of Waitangi was signed at Parliament ", 'no'),
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes'))


score = 0
maxQuestions = 0
while maxQuestions <= 0 or maxQuestions > len(questions):
    try:
        maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
    except Exception as e:
        print(e)
        print("Please enter an integer value.")
        maxQuestions = 0
for count, (q, right) in enumerate(questions):
    if count >= maxQuestions:
        break
    elif input(q).lower() == right:
        print("Well done! You got it right!")
        score += 1
    else:
        print("You got it wrong this time!")
print("Your score is {} points".format(score))

Hey,

I tried to run the code you've posted and it shows an indentation error. Is this the way that DaniWeb has formatted it, or, is it your code?

I don't get what you're trying to ask, is your question regarding the fact that "random" cannot be imported, or, to do with the random function? Please POST the ERROR message that you get (if any) :)

When you say that import random failed, just what do you mean? If you got an error message, post it with the full traceback. Otherwise, did it simply not do what you expected it to?

I would recommend using the random.shuffle() function on the series of questions; however, to do that, you'll need to make a small change, which is to make the outer tuple holding the question-answer pairs into a list.

questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]

random.shuffle(questions)    # automagically rearrange the questions in a random order

Note that all I did was change one pair of parentheses to a pair of square brackets, and add the call to random.shuffle(). The reason for changing questions from a tuple to a list is simply that tuples are immutable: once they are created, they cannot be altered. You can reassign a different value to the variable, but you can't change the tuple itself. Lists, on the other hand, are mutable, so the shuffle() function can work on them.

I would recommend using the random.shuffle() function on the series of questions; however, to do that, you'll need to make a small change, which is to make the outer tuple holding the question-answer pairs into a list.

And why should he, works for me OK with tuple, but I would take random.sample.

Yes, but sample() returns a list of samples out of the tuple; it doesn't modify the tuple itself, the way shuffle() does. When I ran shuffle on a tuple, I got the following traceback:

>>> random.shuffle((1, 2, 3, 4))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\random.py", line 288, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item assignment

I have to admit that sample() is in some ways a better solution, as you can use it to limit the size of the questions list, obviating the need for the enumerate(). I wish I'd thought of using it myself.

Why would you shuffle, if you do not want sample, then you would actually use random.choice. I misread you.

In retrospect, I would have used sample() had I thought of it. I was thinking mainly in terms of reorganizing the entire 'deck' of questions, but your solution makes more sense.

My hunch is that the problem dean.ong.14 (Dean Ong) encounters is caused by a user file saved as random.py, something to be avoided.

it works now. how to make sure that people canquit in the middle of the quiz?

Recognizing some answer like quit as special and doing break from the loop.

Can you edit my coding? Thx

@dran.ong.14 - Be greatful that people are taking time out of their busy lives to help you, rather than being forward and asking someone to literally spoon-feed you the fix.

i still can't get it right.. keep failing. here is my new coding

# make input equal to Python3 style input even in Python2
import random
try:
    input = raw_input
except:
    pass
print("Welcome to my yes or no quiz!")
questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
    ("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
    ("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
    ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
    ("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
    ("The All Blacks are New Zealands top rugby team ", 'yes'),
    ("The Treaty of Waitangi was signed at Parliament ", 'no'),
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]
random.shuffle(questions) # automagically rearrange the questions in a random order
score = 0
maxQuestions = 0
while maxQuestions <= 0 or maxQuestions > len(questions):
    try:
        maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
    except Exception as e:
        print(e)
        print("Please enter an integer value.")
        maxQuestions = 0
for count, (q, right) in enumerate(questions):
    if count >= maxQuestions:
        break
    elif input(q).lower() == right:
        print("Well done! You got it right!")
        score += 1
    else:
        print("You got it wrong this time!")
print("Your score is {} points".format(score))
    else:
        raw_input:("quit to exit this program"))

You got else for a print statement and totally out of syntax line 40 also.

# make input equal to Python3 style input even in Python2
import random
try:
    input = raw_input
except:
    pass
print("Welcome to my yes or no quiz!")
questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
    ("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
    ("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
    ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
    ("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
    ("The All Blacks are New Zealands top rugby team ", 'yes'),
    ("The Treaty of Waitangi was signed at Parliament ", 'no'),
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]
random.shuffle(questions) # automagically rearrange the questions in a random order
score = 0
maxQuestions = 0
while maxQuestions <= 0 or maxQuestions > len(questions):
    try:
        maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
    except Exception as e:
        print(e)
        print("Please enter an integer value.")
        maxQuestions = 0
for count, (q, right) in enumerate(questions):
    if count >= maxQuestions:
        break
    elif input(q).lower() == right:
        print("Well done! You got it right!")
        score += 1
    else:
        print("You got it wrong this time!")
print("Your score is {} points".format(score))
    else:
        print("quit to exit this program")
commented: Come on try to get at least syntax correct! -3

here is my new coding.. i not sure how to make sure people can quit in the middle of the game so i tell them they can't quit if they start

# make input equal to Python3 style input even in Python2
import random


try:
    input = raw_input
except:
    pass
print("Welcome to my yes or no quiz!")
begin= input("would you like to begin?:")
if begin == "yes":
    print ("")
else:
    print("thanks for trying my quiz, Good bye :")
questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
    ("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
    ("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
    ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
    ("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
    ("The All Blacks are New Zealands top rugby team ", 'yes'),
    ("The Treaty of Waitangi was signed at Parliament ", 'no'),
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]
random.shuffle(questions) # automagically rearrange the questions in a random order
score = 0
maxQuestions = 0
while maxQuestions <= 0 or maxQuestions > len(questions):
    try:
        maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
    except Exception as e:
        print(e)
        print("Please enter an integer value.")
        maxQuestions = 0
for count, (q, right) in enumerate(questions):
    if count >= maxQuestions:
        break
    elif input(q).lower() == right:
        print("Well done! You got it right!")
        score += 1
    else:
        print("You got it wrong this time!")
print("Your score is {} points".format(score))

I have structured code better by using functions and some changes/corrections.
This make it easier to test code and as you want start and stop the quiz.

import random

try:
    input = raw_input
except:
    pass

def all_quest():
    '''All questions that can be used'''
    questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
    ("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
    ("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
    ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
    ("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
    ("The All Blacks are New Zealands top rugby team ", 'yes'),
    ("The Treaty of Waitangi was signed at Parliament ", 'no'),
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]
    random.shuffle(questions)
    return questions

def numb_of_quest(questions):
    '''Return the number of questions to be asked'''
    while True:
        try:
            maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
            if 0 <= maxQuestions < len(questions):
                return (maxQuestions)
            else:
                print('Not between 0 and {},try again\n'.format(len(questions)))
        except Exception as e:
            print("Please enter an integer value,try again\n")

def quest_loop(questions,maxQuestions):
    '''Run questions and return score of right answers'''
    score = 0
    score_lst = []
    for count, (q, right) in enumerate(questions):
        if count >= maxQuestions:
            return(score_lst)
        elif input(q).lower() == right:
            print("Well done! You got it right!\n")
            score += 1
            score_lst.append(score)
        else:
            print("You got it wrong this time!\n")

def menuloop():
    '''Main menu of question quiz'''
    while True:
        print( 'Welcome to my yes or no quiz!')
        print( '(1) Play question quiz')
        print( '(2) Show last score')
        print( '(q) Quit\n')
        choice = input('Enter your choice: ')
        if choice == '1':
            questions = all_quest()
            maxQuestions = numb_of_quest(questions)
            score = quest_loop(questions,maxQuestions)
        elif choice == '2':
            try:
                print('Out of {} question you got {} right answers\n'.format(maxQuestions, len(score)))
            except UnboundLocalError:
                pass
        elif choice.lower() in ('q', 'quit'):
            return False
        else:
            print('Not a correct choice {},try again\n'.format(choice))

if __name__ == '__main__':
    menuloop()

Looks lke Snippsat's code addresses all the problems of this thread.

not really coz it still dont allowed people to type quit to quit in the middle of the quiz.. but still it helped me alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.