【问题标题】:Python: Raw_Input inside an if statement?Python:if 语句中的 Raw_Input?
【发布时间】:2014-12-07 04:41:30
【问题描述】:

我从 python 开始。当我将新的 raw_input 放入 if 语句中时,我不断收到错误消息。如果他们回答的输入不正确,我想再给他们一次输入更多输入的机会,还有其他方法吗?

代码如下

attraction = {
    'approach' : "words",
    'introduction' : "words",
    'qualification' : "words",
    'rapport' : "words"
}

answer = raw_input("Pick from these approaches: introduction, qualification, or rapport:")

if answer != "approach" and answer != "introduction" and answer != "qualification" and answer != "rapport":
    new_answer = raw_input("You didn't choose one of the choices, type in the choice you want again:")
if new_answer != "approach" and answer != "introduction" and answer != "qualification" and answer != "rapport":
    print "That was your last chance buddy"
else:
    print attraction[answer]

【问题讨论】:

  • 将原始输入放在一个while循环中。有答案时使用 break
  • 我知道这不是一个相关的问题,但是,请问您为什么开始学习 Python 2.7?为什么不是 Python 3?
  • 与您的问题无关:写起来更容易:if answer not in ("approach", "introduction", "qualification", "rapport"):
  • 我认为你应该使用 or 表达式而不是 `and' 因为单个输入不能是 3 种不同的类型。
  • 你也可以if answer not in attraction.keys():

标签: python if-statement input


【解决方案1】:

第二次询问时无需创建新变量new_answer,只需将answer 设置为新值即可:

answer = raw_input("You didn't choose one of the choices, type in the choice you want again:")

并在程序中的其他地方将new_answer 替换为answer

我会使用.keys() 方法来执行这样的程序:

attraction = {
    'approach' : "words",
    'introduction' : "words",
    'qualification' : "words",
    'rapport' : "words"
}

answer = raw_input("Pick from these approaches: introduction, qualification, or rapport:")

while not answer in attraction.keys():
    answer = raw_input("You didn't choose one of the choices, type in the choice you want again:")

print attraction[answer]

【讨论】:

  • 你甚至不需要使用.keys()。根据定义,字典会遍历它的键 - 所以你可以简单地使用 while not answer in attraction:
  • 这就是我没有实际运行答案中的代码。
  • @PeterWood 请注意,循环中的raw_inputs 的提示与初始提示不同。
【解决方案2】:

你可以简单地写:

while True:
    answer = raw_input("Pick from these approaches: introduction, qualification, or rapport:")
    if answer == "approach" or answer == "introduction" or answer == "qualification" or answer == "rapport":
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2013-10-26
    • 2018-08-11
    • 2016-10-16
    • 1970-01-01
    • 2013-10-12
    • 2016-08-30
    相关资源
    最近更新 更多