如何在python中创建多个不等式?例如。
school_type = input ("Enter what type of school you want. press H for high school, M for middle school, or E for elementary school").lower()
while school_type != "h" or school_type != "m" or school_type != "e": # Is this code correct?
print ("You must enter H, M, or E")
答案 0 :(得分:3)
school_type != "h" or school_type != "m"
将始终评估为True
,因为school_type
将始终不等于"h"
或不等于"m"
。
您应该在while-loop条件中使用and
而不是or
:
while school_type != "h" and school_type != "m" and school_type != "e":
那,或者您可以使用not in
:
while school_type not in {"h", "m", "e"}:
答案 1 :(得分:2)
正如@iCodez所说,如果school_type
与"h"
不同,并且与"m"
不同,而且与"e"
不同,则需要再次进行迭代。正如他所说,用school_type not in ["h", "m", "e"]
之类的东西可以更好地表达出来。该表达式更简单,更易于阅读且不易出错。
更改while
条件后,我仍然会在代码中修复两件事。首先,如果条件为真,即用户为school_type
键入了错误的值,则应采取适当的操作:必须要求用户键入新值,直到他/她键入正确的值为止。其次,您应该使用raw_input()
而不是input()
。区别在于第一个更适合字符串,而第二个是有问题的,在这种情况下实际上需要用户在输入值周围键入"
。
结果可能是这样的:
def ask_for_school_type():
s = "Enter what type of school you want. Type H for high \
school, M for middle school, or E for elementary school: "
return raw_input(s).lower()
school_type = ask_for_school_type()
while school_type not in ["h", "m", "e"]:
print "You must enter H, M, or E"
school_type = ask_for_school_type()