while循环不断重复python

时间:2016-05-04 11:10:59

标签: python while-loop

我一直在制作一个非常简单的程序,询问用户是否喜欢苹果或橙子。如果用户写苹果,您将收到消息'您更喜欢苹果',反之亦然橙子。如果用户未能写出苹果'或者'橘子'他们会被提示再次这样做。

出于某种原因,无论用户是否写了“苹果”等。或者'橘子'它仍会促使他们再次写下他们的答案。 Here is an example.

这是我的代码:

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)

6 个答案:

答案 0 :(得分:5)

您的问题会重复这个问题,只要SELECT dbms_lob.substr( column_name, dbms_lob.getlength(column_name), 1) FROM foo 等于answer 是真的,那么'apples' answer。如果您回答 apples ,那么'oranges'不等于answer,那么循环重复。将'oranges'更改为or的一个明显的解决方案。

然而,更加pythonic的解决方案是使用and运算符和 set literal ; (你也不需要在这里重复not in)。因此:

input

(PS我重命名了您的变量,因为您作为参数提供给answer = None while answer not in {'apples', 'oranges'}: answer = input('Do you prefer apples or oranges? ').lower() 的文本是问题input返回答案对那个问题。)

答案 1 :(得分:0)

or交换and,使其成为

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

答案 2 :(得分:0)

question'apples'不同或与'oranges'不同,因为它不能同时与两者同等。

你要表达的是:

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)

答案 3 :(得分:0)

您可以使用in运算符来避免为每个水果重复quesiton != ...

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

E.g。

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

或事先声明“水果单”:

fruits = ["apples", "oranges"]

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

答案 4 :(得分:0)

如果左侧的术语等于右侧序列中的一个元素,则可以使用返回in的{​​{1}}运算符来简化逻辑

True

P.S。 answer = '' while answer not in ('oranges', 'apples'): answer = input('...') 当两个术语都是字符串时的行为不同,如果左项是右项的子字符串,则返回in

答案 5 :(得分:0)

试试这个:

while not ((question=='apples') or (question=='oranges')):
相关问题