简体   繁体   中英

Tip calculator issue

trying to write a python code for a tip calculator based on service and I'm running into an issue with my while loop.

service = ""
while service != "excellent" or service != "good" or service != "bad":
    service = input("(Please choose excellent, good, or bad): ")

This part is causing an infinite loop, but I'm not sure why or how to fix it...

You are using or where you want to use and .

The loop is going to continue if any one of the three conditions is true.

If your input is "excellent" then service != "good" and service != "bad" are both going to be true so the loop will continue. The same is true for the other values.

What you want is:

service = ""
while service != "excellent" and service != "good" and service != "bad":
    service = input("(Please choose excellent, good, or bad): ")

Even better (and more Pythonic as various commenters have pointed out) is:

service = ""
while service.lower() not in ["excellent", "good", "bad"]:
    service = input("(Please choose excellent, good, or bad): ")

This reads easier and also accepts inputs in any case (upper, lower, mixed).

In this situation you want to use "and" rather than "or". Another option, though, that is cleaner would be to do this:

while service not in ['excellent', 'good', 'bad]:
    service = input('(Please choose excellent, good, or bad): ')

This will test whether the value of service is in the list of acceptable answers and makes it easier to edit later.

Right now, you're saying "if any three of these statements is true, continue the while loop".

What you want is:

service = ""
while service != "excellent" and service != "good" and service != "bad":
    service = input("(Please choose excellent, good, or bad): ")

You just have your logic a bit mixed up - you are using or instead of and .

Whatever input you have, it will be (not excellent) or (not good) or (not bad)!

For example, even if you input "good", good is (not excellent) and thus the overall condition returns True, and you'll keep looping.

A clearer way to write this condition is:

while service not in ["excellent", "good", "bad"]:
    service = input("(Please choose excellent, good, or bad): ")

To loop until any of a number of conditions is met (because it is neither possible nor meaningful to meet all of them at once), you need to loop while all of them are not met (logical negation). The most readable and pythonic way to express this that I can think of is:

service = ''
while service not in ('excellent', 'good', 'bad'):
    service = input("(Please choose excellent, good, or bad): ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM