1

I am having problems including multiple statements with while loop in python. It works perfectly fine with single condition but when i include multiple conditions, the loop does not terminate. Am i doing something wrong here?

name = raw_input("Please enter a word in the sentence (enter . ! or ? to end.)")

final = list()

while (name != ".") or (name != "!") or (name != "?"):
    final.append(name)
    print "...currently:", " ".join(final)
    name = raw_input("Please enter a word in the sentence (enter . ! or ? to end.)")
print " ".join(final)

2 Answers 2

4

You need to use and; you want the loop to continue if all conditions are met, not just one:

while (name != ".") and (name != "!") and (name != "?"):

You don't need the parentheses however.

Better would be to test for membership here:

while name not in '.!?':
Sign up to request clarification or add additional context in comments.

Comments

2

This condition:

(name != ".") or (name != "!") or (name != "?")

is always true. It could only be false of all three subconditions were false, which would require that name were equal to "." and "!" and "?" simultaneously.

You mean:

while (name != ".") and (name != "!") and (name != "?"):

or, more simply,

while name not in { '.', '!', '?' }:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.