-1

I have written this very simple code so far but before I started expanding it, I have noticed that the while loop runs for one more time even though it should break.

x = 2
answer = None
prompt = "> "

while True:
    print(x)

    x = x + 1

    if answer not in ["no", "NO", "nO", "No"]:
        print("Continue?")
        answer = input(prompt)
    else:
        break

This is what I get when I run the code:

2
Continue?
> no
3

I would expect that the "3" would not show because the while loop should already be escaped from. What am I not understanding here?

jps
  • 20,041
  • 15
  • 75
  • 79
marta
  • 1
  • 2
  • You only check the answer during the next iteration of the loop so why are you surprised it only breaks during the next iteration?? – luk2302 Mar 20 '23 at 21:07
  • Totally get it now thanks! That's so simple :) Have an amazing day! – marta Mar 20 '23 at 21:09
  • BTW, [How do I do a case-insensitive string comparison?](https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison) – Ignatius Reilly Mar 20 '23 at 21:56

1 Answers1

0

You checked the answer in the next iteration when you should have checked it right behind the input.

Here is the fixed and simplified code:

x = 2
prompt = "> "

while True:
    print(x)

    x += 1

    print("Continue?")
    answer = input(prompt)
    if answer.lower() == "no":
        break
Thoosje
  • 1
  • 1