【问题标题】:Gathering input using raw_input in Python在 Python 中使用 raw_input 收集输入
【发布时间】:2013-11-14 18:11:02
【问题描述】:

所以我正在尝试使用raw_input 获取程序的输入,我有:

def Input1(time):

    userInput = raw_input()
    print ("Please choose either morning or night: ")

    if userInput != "morning" or "night":
        print ("Invalid entry. Select again")
        Input1(time)

    if userInput in "morning" or "night":
        Input2(year)

第二个if 语句提示它进行更多编程。

当我尝试运行这个程序时,它会运行一切,但它不会要求用户输入任何内容。有什么想法吗?

虽然它没有显示,但所有内容都在def Input1(time): 下标出

【问题讨论】:

  • 你在打电话给Input1吗?要缩进,您需要在每行代码前使用 4 个空格,因为这是您将代码添加到 SO 帖子的方式。
  • if userInput in "morning" or "night": 应该是if userInput in ['morning, 'night']: if userInput == 'morning' or userInput == 'night':。就目前而言,该行等同于if userInput in 'morning' or 'night' == True:,这当然总是正确的。 (PS:'mor' in 'morning' == True

标签: python input python-2.x


【解决方案1】:

这段代码不好有很多原因:

def Input1(time):

函数名不应以大写字母开头。

userInput = raw_input()
print ("Please choose either morning or night: ")

简单写成:userInuput = raw_input("请选择早上或晚上:")

if userInput != "morning" or "night":

这相当于:

if userInput != "morning" or True:

这总是正确的......

    print ("Invalid entry. Select again")
    Input1(time)

在这里,您进行递归调用,再次询问...但是没有任何返回,这意味着将多次调用以下内容(实际上没有,因为您无法退出该函数)。

if userInput in "morning" or "night":
    Input2(year)

同样的错误,应该是:

if userInput in ["morning", "night"]:

if userInput == "morning" or userInput == "night":

【讨论】:

    【解决方案2】:

    您可以在raw_input 调用中加入提示:

    userInput = raw_input("Please choose either morning or night: ")
    

    对于这个逻辑:if userInput != "morning" or "night" 你实际上想要if userInput != "morning" and userInput != "night"。另一种写法是`if userInput not in ('morning', 'night')。类似的逻辑适用于您的第二个 if 语句。

    【讨论】:

      【解决方案3】:

      您在运行代码时实际上是在调用 Input1(time) 吗?不调用它就不会运行。

      【讨论】:

        【解决方案4】:

        查看运算符的顺序。首先,您要求用户输入;之后,您打印“请选择”提示。因此,在用户输入值之前不会出现此提示。正确的做法:

        userInput = raw_input("Please choose either morning or night:")
        

        此外,据我了解,您在if 语句中的条件不正确。请参阅有关 inor 运算符的 Python 文档。

        【讨论】:

          【解决方案5】:

          raw_input() 更名为input()

          来自http://docs.python.org/dev/py3k/whatsnew/3.0.html

          【讨论】:

          • ... 在 Python 3 中。如果他使用 Python 3 和 raw_input,他的代码会抛出错误。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多