-4

I am very new to programming so possibly its just basic syntax problem i am having or may be unfamiliarity with functions which is limiting my ability but here is the questions. I found following program in a youtube tutorial in which tutor created a multiple choice questions test with 3 possible answers using class method. here is the original code:

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer


question_prompts = [
    'What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n',
]

questions = [
    Question(question_prompts[0], 'a'),
    Question(question_prompts[1], 'c'),
    Question(question_prompts[2], 'b'),
]


def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)

    if answer == question.answer:
            score +=1

print('You got ' + str(score) + '/' + str(len(questions)) + ' correct')



run_test(questions)

Original code allows the user to attempt each question only once and scores out of a total of 3 in the end.

The Problem:

I want to add a conditional statement/loop (before score counting if statement) to check if the user has entered correct choice of either 'a' or 'b' or 'c'. If the user enters anything other than a or b or c then it must stay in the loop infinitely and ask the user to enter correct choice of either a or b or c.

i tried while loop but it doesn't break, even if user enter correct choice of either a or b or c. Please help

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
  • 5
    You're posting code that you haven't written which does work but referring to code that you have written that doesn't work. Why not post the code that you have written, since that is the code which has the actual problem? Please read about how to make a [mcve]. – John Coleman Nov 28 '19 at 01:50
  • 1
    Welcome to Stack Overflow! Check out the [tour]. Like John said, we're not mind readers. You need to provide your non-working code as a [mre]. See [ask] for other tips. – wjandrea Nov 28 '19 at 01:52
  • On second thought, this might be a duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658/4518341) – wjandrea Nov 28 '19 at 01:53
  • 2
    In addition to what the others are saying (I agree) - don't be afraid to share 'bad code'; people here tend to be happy to help you improve and you'll learn the most by sharing your attempts, even if you're not (yet) proud of them. – Grismar Nov 28 '19 at 01:55

3 Answers3

0

You can add an if condition inside an infinite while loop to break out of it.

Also your run_test() function must return the score, see below:

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

def run_test(questions):
    score = 0
    for question in questions:
        while True:
            answer = input(question.prompt)
            if answer in ['a', 'b', 'c']:
                break

        if answer == question.answer:
            score +=1

    return score

question_prompts = ['What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
                    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
                    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n']

questions = [Question(question_prompts[0], 'a'),
             Question(question_prompts[1], 'c'),
             Question(question_prompts[2], 'b')]

score = run_test(questions)
print("\nYou got {}/{} correct".format(score, len(questions)))

Sample Output:

What color are apples?
(a) Red/Green
(b) Purple
(c) Orange

a
What color are Bananas?
(a) Teal
(b) Magenta
(c) Yellow

b
What color are Strawberries?
(a) Yellow
(b) Red
(c) Blue

c

You got 1/3 correct
lbragile
  • 7,549
  • 3
  • 27
  • 64
0

You can use a while loop inside of the for loop, and with each new question set it so that it will only loop if the input is wrong.

This should be what you are looking for.

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

score = 0

question_prompts = [
    'What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n',
]

questions = [
    Question(question_prompts[0], 'a'),
    Question(question_prompts[1], 'c'),
    Question(question_prompts[2], 'b'),
]

def run_test(questions):
    score = 0

    for question in questions:
        wrong = True
        while wrong == True :
            answer = input(question.prompt)

            if answer == question.answer:
                    score +=1
                    wrong = False

print('You got ' + str(score) + '/' + str(len(questions)) + ' correct')



run_test(questions)
CanadianCaleb
  • 136
  • 10
0

Firstly, this program will crash when you reference score in your final print line. This is because score is a local variable inside of run_test() and isn't accessible outside of that function, there are a lot of ways around this, but a quick and dirty one to start with would just be to move score = 0 outside of run_test() and then once inside run_test() add global score, this should mean that score exists in the same "scope" as the print statement, and the global score statement means run_test() will know to look outside of its scope to find the variable to use.

Now for your actual question, you can solve this problem very simply by adding a while True: around your answer input and calling break if the answer is correct.

You also currently should be adding to the score for every question, not just at the end, so that should be inserted into the for loop.

Finally, you are referencing score before the function that figures it out is actually called; even if the function is defined above another bit of code, the code in that function wont run until that function is called.

Here is a working piece of code:

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer


question_prompts = [
    'What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n',
]

questions = [
    Question(question_prompts[0], 'a'),
    Question(question_prompts[1], 'c'),
    Question(question_prompts[2], 'b'),
]

score = 0

def run_test(questions):
    global score
    for question in questions:
        while True:
            answer = input(question.prompt)
            if answer == question.answer:
                print("Correct!")
                score +=1
                break
            else:
                print("Incorrect, please try again")





run_test(questions)

print('You got ' + str(score) + '/' + str(len(questions)) + ' correct')
Fyrefly
  • 88
  • 7