【问题标题】:If statement not working for raw_input prompt如果语句不适用于 raw_input 提示
【发布时间】:2016-10-30 19:22:57
【问题描述】:

显示的所有内容都是正确的,因为我之前测试过...

不管我说什么,它仍然说“这不是一个选择”,这是我的 else 声明

1 = 选择1

2 = 选择2

3 = 选择3

while True:
    choice = raw_input("->")
    if choice == 1:
        dochoice1
        break
    elif choice == 2:
        dochoice2
        break
    elif choice == 3:
        dochoice3
        break
    else:
        print "That Is Not A Choice"
        continue

【问题讨论】:

  • 所以无论我说什么,它仍然说“这不是一个选择”,这是我的 else 声明......
  • @DuckyQuack if 不重复,因此它不是循环构造

标签: python if-statement python-2.x adventure


【解决方案1】:

raw_input 返回一个字符串,将其与整数进行比较,将choice 转换为int,或将其与字符串进行比较:

choice = int(raw_input("->"))

或:

if choice == "1":

如果用户输入的内容不是有效的int,您可以捕获异常:

try:
    choice = int(raw_input("->"))
except ValueError:
    print "Invalid int"
    continue

【讨论】:

  • 为什么不直接使用返回intinput
  • @EliSadoff 在 Python 2 中使用 input 是不好的做法,因为它会调用 eval
  • 但是当我这样做时,如果回复或输入不是整数,则代码中有错误
  • @FranciscoCouzo 是的。它还允许更多的 UB。
  • 我试着把它变成一个字符串,但它只是浪费了 20 秒或几秒钟,然后说代码完成了
猜你喜欢
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多