python中带多个条件的While循环

2024-06-11 22:04:15 发布

您现在位置:Python中文网/ 问答频道 /正文

weatherType = raw_input('Enter a weather type: ')

while (weatherType != "WINDDIRECTION") or (weatherType != "WINDSPEED") or (weatherType != "AIRTEMPERATURE") or (weatherType != "WAVEHEIGHT") or (weatherType != "AIRPRESSURE"):
    print "Sorry, invalid input. Please enter AIRTEMPERATURE, AIRPRESSURE, WAVEHEIGHT, WINDSPEED, or WINDDIRECTION  for a city and either WINDDIRECTION, WINDSPEED, or AIRTEMPERATURE for an off shore bouy"
    weatherType = raw_input('Enter a weather type: ')

好的,在这个循环中,我试图让用户输入WINDDIRECTIONWINDSPEEDAIRTEMPERATUREWAVEHEIGHT,或{}。但是,即使用户在这5个选项中输入1个,我的代码仍然会进入while循环。我不知道发生了什么事。 我知道我可以使用for循环(for x in[“WINDDIRECTION”…..]),但是for循环只会检查他们第一次输入是否正确,如果他们再次输入错误答案,代码将继续


Tags: or用户forinputrawtypeenterweather
3条回答

除了李·丹尼尔·克罗克。在

看看织物包装。有很好的工具来管理控制台输入。在

from fabric.contrib import console

def validate(v):
    answers = ['WINDDIRECTION',...]
    if v in answers:
        return int(v)

question = 'Enter a weather type: '

console_prompt = console.prompt(question, default="WINDDIRECTION", validate=validate)

您的代码继续进入循环,因为您希望“weatherType”var获取预定义值之一(“WINDDIRECTION”等)。但是,不管用户提供什么输入,WHILE条件总是满足的(因为“weatherType”一次只有一个值,它将匹配WHILE“or”条件,因此进入循环)。在

或者,您可以创建一个包含所有选项的列表['WINDDIRECTION'、''等],并检查列表中是否有用户输入。在

示例:

options = ["WINDDIRECTION", "WINDSPEED", "AIRTEMPERATURE", "WAVEHEIGHT", "WAVEHEIGHT"]

message = '''Sorry, invalid input. Please enter:
AIRTEMPERATURE, AIRPRESSURE,
WAVEHEIGHT, WINDSPEED, or WINDDIRECTION  for a city and either
WINDDIRECTION, WINDSPEED, or AIRTEMPERATURE for an off shore bouy
'''

weatherType = raw_input('Enter a weather type: ')

while weatherType not in options:
    print message
    weatherType = raw_input('Enter a weather type: ')
(x != y) or (x != z) ...

永远都是真的。由于您使用的是Python,我建议您改用in

^{pr2}$

相关问题 更多 >