0

I am pretty new to Python and I am having trouble with this 'quiz' I am creating.

answer_1_choices = {
    'A' : 'A: A list is a datatype that stores a sequence of items with individual indexes that are mutable.',
    'B' : 'B: A list is a datatype that stores a sequence of items with individual indexes that are immutable.',
    'C' : 'C: A list is a datatype that stores a sequence of items assigned to individual keys that are immutable.'
    }
Number_One = '1. What is a list?'

def answer():
    x = input()
    if x == 'A' or x == 'a':
        print('Correct!')
    else:
        print('That is an incorrect response.  Please try again.' + '\n' + '\n' + Number_One + '\n')
        print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
        print('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')

def question_one():
    print(Number_One + '\n')
    print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
    print('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')


question_one()
answer()

I want the else statement to run infinitely every time that the input is something other than 'A' or 'a'. I know I have to use some kind of loop or something, but I just can't seem to figure it out. Can someone help me?

Daniel
  • 42,087
  • 4
  • 55
  • 81
SunGone
  • 29
  • 3

2 Answers2

7

What you're thinking of there is a while loop. Instead of checking for x = 'A' or x = 'a', you might try testing for whether x isn't 'A' or 'a'.

Try this:

while (x != 'A' and x != 'a'):
    print('That is an incorrect response.  Please try again.' + '\n' + '\n' + Number_One + '\n')
    print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
    x = input('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')
print('Correct!')

This way, it will only print "Correct!" once the breaking condition has been satisfied.

Daniel
  • 42,087
  • 4
  • 55
  • 81
awb
  • 106
  • 1
  • 5
-1

Add as the last line of the else case a recursive call:

 answer()

Full code:

def answer():
    x = input()
    if x == 'A' or x == 'a':
        print('Correct!')
    else:
        print('That is an incorrect response.  Please try again.' + '\n' + '\n' + Number_One + '\n')
        print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
        print('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')
        answer()
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Tal
  • 145
  • 8
  • 1
    Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/161132/discussion-on-answer-by-tal-how-do-i-loop-this-else-statement). – Brad Larson Dec 13 '17 at 17:52