【问题标题】:How do I limit user input to two possible strings? [duplicate]如何将用户输入限制为两个可能的字符串? [复制]
【发布时间】:2020-01-13 19:24:18
【问题描述】:

我正在编写一个简单的算法来在摄氏度和华氏度之间进行转换,只要 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()。我显然不想那样。

【问题讨论】:

    标签: python string python-2.7 comparison


    【解决方案1】:

    你的条件有错误,应该是

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2020-08-07
      相关资源
      最近更新 更多