Reputation: 2189
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)
Upvotes: 1
Views: 5312
Reputation: 59096
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 { '.', '!', '?' }:
Upvotes: 2
Reputation: 1121306
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 '.!?':
Upvotes: 4