如何将用户输入限制为两个可能的字符串?

How do I limit user input to two possible strings?

我正在编写一个简单的算法来在摄氏度和华氏度之间进行转换,只要 tu 的输入限制为 "F" 或 "C",算法的其余部分就可以完美运行。但是我实际上想阻止用户输入这些字符串以外的任何内容。

我想用会触发错误消息的内容替换注释区域 sys.exit()

import sys
t = 0.0
tu = "null"

print "This program will convert between degrees C and F." 

print "Input temperature unit. (F or C)"
tu = raw_input()
#if (tu != "F" and != "C"):
    #print "The directions were clear, try again."
    #sys.exit()


即使是应该允许的输入也会触发 sys.exit()。我显然不想那样。

你的条件有误,应该是

if tu != "F" and tu != "C":

要检查变量是否是多个值之一,您可以使用 in

if tu not in ('F', 'C'):