简体   繁体   中英

While loop keeps repeating python

I've been making a very simple program which asks the user if they prefer apples or oranges. If the user writes apples, you will receive the message 'You prefer apples', and vice versa with oranges. If the user fails to write either 'apples' or 'oranges' they will be prompted to do it again.

For some reason however, regardless of if the user wrote 'apples' or 'oranges' it will still prompt them to write in their answer again. Here is an example.

Here is my code:

question = input('Do you prefer apples or oranges? ').lower()

while question!='apples' or question!='oranges':
    question = input('Do you prefer apples or oranges? ').lower()

print('You prefer ' + question)

Your question repeats the question for as long as it is true that answer is not equal to 'apples' or it is true that the answer is not 'oranges' . If you answer apples , it is true that answer is not equal to 'oranges' then, so the loop repeats. One obvious solution to change or to and .

However a more pythonic solution is to use the not in operator with a set literal ; (also you do not need to repeat the input here). Thus:

answer = None
while answer not in {'apples', 'oranges'}:
    answer = input('Do you prefer apples or oranges? ').lower()

(PS I renamed your variable, since the text that you give to input as an argument is the question , and input returns the answer to that question.)

交换or用于and使之成为

question!='apples' and question!='oranges'

It is always the case that question is different from 'apples' or different from 'oranges' , because it cannot be equal to both at the same time.

What you want to express is this:

question = input('Do you prefer apples or oranges? ').lower()

while question not in ('apples', 'oranges'):
    question = input('Do you prefer apples or oranges? ').lower()

print('You prefer ' + question)

You can use the in operator to avoid repeating quesiton != ... for every fruit:

while question not in LIST/SET/TUPLE/DICTIONARY/STRING:

Eg

while question not in ["apples", "oranges"]:
    question = input('Do you prefer apples or oranges? ').lower()

Or declare a "fruit list" beforehand:

fruits = ["apples", "oranges"]

while question not in set(fruits):
    question = input('Do you prefer apples or oranges? ').lower()

You can simplify your logic using the in operator that returns True if the term on its left is equal to one of the elements of the sequence on its right

answer = ''
while answer not in ('oranges', 'apples'):
    answer = input('...')

ps the behavior of in when both terms are strings is different, it returns True if the left term is a substring of the right term.

尝试这个:

while not ((question=='apples') or (question=='oranges')):

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