0

What would I do here to get my code to go back an iteration?

list_ = [3,'yes',True]
for x in range(len(list_)):
    print('What is the next item in the list?')
    answer = input()
    if answer = list_[x]:
        print('Good job!')
    else:
        print('Nope! Try again.')

At that very last portion of the code (the 'else' statement) how would I get it to go over the same iteration of the for loop again so that the user can try again?

martineau
  • 119,623
  • 25
  • 170
  • 301
Adam C
  • 1
  • 1
  • 2
    You can't really do that to the `for` loop, but you can add another `while` loop inside it that keeps prompting until the outer loop can continue. – Ry- May 24 '17 at 01:43

2 Answers2

1

You can't repeat an iteration, per se. What you can do is loop over the prompt until you get the right answer.

for x in range(len(list_)):
    while True:
        print('What is the next item in the list?')
        answer = input()
        if answer == list_[x]:
            print('Good job!')
            break
        else:
            print('Nope! Try again.')

By the way, looping over the indices of the list isn't necessary, at least not in this sample code. It'd be more idiomatic to loop over the list items directly.

for x in list_:
    while True:
        print('What is the next item in the list?')
        answer = input()
        if answer == x:
            print('Good job!')
            break
        else:
            print('Nope! Try again.')
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

If you don't want a while loop you could define your loop in a method with a flag that will call itself again if the answer is incorrect. The while loop is probably a nicer way to handle this though.

    def askQuestions():
        list_ = [3,'yes',True]
        allcorrect = True
        for x in range(len(list_)):
            print('What is the next item in the list?')
            answer = input()
            if answer == list_[x]:
                print('Good job!')
            else:
                print('Nope! Try again.')
                allcorrect = False
                break
        if not allcorrect:
            askQuestions()

askQuestions()
Benjamin Commet
  • 350
  • 3
  • 8