small code redundancy within while-loops (doesn't feel clean)

Posted by wallacoloo on Stack Overflow See other posts from Stack Overflow or by wallacoloo
Published on 2010-05-31T03:47:36Z Indexed on 2010/05/31 3:52 UTC
Read the original article Hit count: 263

So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often:

the_input = raw_input("what to print?\n")
while the_input != "quit":
    print the_input
    the_input = raw_input("what to print?\n")

Maybe I'm being too picky, but I don't like how the line the_input = raw_input("what to print?\n") has to get repeated. It decreases maintainability and organization. But I don't see any workarounds for avoiding the duplicate code without further decreasing the problem. In some languages, I could write something like this:

while ((the_input=raw_input("what to print?\n")) != "quit") {
    print the_input
}

This is definitely not Pythonic, and Python doesn't even allow for assignment within loop conditions AFAIK.

This valid code fixes the redundancy,

while 1:
    the_input = raw_input("what to print?\n")
    if the_input == "quit":
        break
    print the_input

But doesn't feel quite right either. The while 1 implies that this loop will run forever; I'm using a loop, but giving it a fake condition and putting the real one inside it.

Am I being too picky? Is there a better way to do this? Perhaps there's some language construct designed for this that I don't know of?

© Stack Overflow or respective owner

Related posts about python

Related posts about organization