Home > Enterprise >  Python: Why is my While loop and Conditional statement still running when condition is no longer tru
Python: Why is my While loop and Conditional statement still running when condition is no longer tru

Time:11-01

I was given the task, "Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text."

The same task examined here.

But according to the testing software, my answer was valid and correct. I received full credit for my code. That would normally make a person happy, but I don't just want full credit. I want full understanding. And that's where you guys come in. Again, the test says I am right, but when I run my code in VS Code, I receive unexpected behavior. Here's my code:

usr_word = ''
break_list = ['d', 'done', 'Done']
while usr_word not in break_list:
    usr_word = input()
    if usr_word in break_list:
        break
    else:
        reversed_word = usr_word[::-1]
        print(reversed_word)

What I thought would happen is when the user supplied 'd', 'done', or 'Done' from the list, the loop would terminate without printing anything to the terminal. But what I found was that the loop DOES terminate, but not before printing the user's string in reverse order. So, if the user types 'Done' for example, the loop breaks, but the terminal prints out 'enoD' first. I didn't expect that, and I cannot figure out why.

CodePudding user response:

In VS code on Windows, using Python 3.10.8, your code terminates when I input "d", "Done", or "done", just as one would expect. Where did you observe the deviant behavior (platform, interpreter version, context)? Thank you.

CodePudding user response:

I ran your code and it works correctly. It doesn't do the weird behavior you're explaining. The only reason it would behave that way is when the if statement and the condition in the while loop both evaluate to "False". Now that doesn't make sense because the conditions are exact opposites, but maybe you can debug and evaluate the statements to see what's happening on your side.

CodePudding user response:

I cannot reproduce the error that you got but may I suggest some improvements to your code? Specifically the while condition seems backwards to me because you evaluate the condition twice per loop. Here is my suggestion:

break_list = ['Done', 'done', 'd']

while True:
    usr_word = input('Enter a word:')
    if usr_word not in break_list:
        print(usr_word[::-1]
    else:
        break
  • Related