【问题标题】:Python 3 unable to get letter inputPython 3 无法获得字母输入
【发布时间】:2014-05-05 13:55:47
【问题描述】:

我正在使用 Enthought Canopy 编译器。我正在尝试使用以下代码从用户那里获取单词输入:

starting_day = str(input("Enter the day you will be leaving: "))

但是,每当我通过运行程序测试 var 时,在为变量分配一串字母后,我总是收到以下错误(当我给它数字时它会运行)

Enter the day you will be leaving: monday

NameError                                 Traceback (most recent call last)

C:\Users\user\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.1.0.1371.win-x86\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
    174             else:

    175                 filename = fname

--> 176             exec compile(scripttext, filename, 'exec') in glob, loc

    177     else:

    178         def execfile(fname, *where):

c:\users\user\appdata\local\temp\tmpnwkfhu.py in <module>()

----> 1 starting_day = str(input("Enter the day you will be leaving: "))

      2 

      3 lenght_of_stay = int(input("Enter the number of days you will say for: "))

      4 

      5 print(starting_day, lenght_of_stay)

<string> in emulated_input(prompt)

<string> in <module>()

NameError: name 'monday' is not defined

【问题讨论】:

  • 怎么改成3
  • 您可能会发现this question 在接受用户输入方面很有用。
  • @user133745:不要在评论中提问,edit你的问题,或者ask a new one
  • @J.F.Sebastian:不是那个问题;寻求建议是题外话,并且将您的问题更改为新问题也是不受欢迎的。编辑问题是为了澄清当前问题,而不是添加新问题。
  • @MartijnPieters:“如何将其更改为 3” 不应该出现在 cmets 到 OP 的问题中。期间。

标签: python python-3.x


【解决方案1】:

您使用的是 Python 2,而不是 Python 3。

在 Python 2 中,input() 将所有输入传递给 eval();字符串 monday 被解释为 Python 名称,它会抛出 NameError,因为它没有定义。

您也可以在回溯中看到这一点; exec 在 Python 3 中是一个函数,在 Python 2 中是一个语句。回溯将其用作语句(无括号)。最重要的是,您使用的是 Enthought Canopy,can only support Python 2

要么改用raw_input(),要么使用实际的 Python 3 解释器运行您的代码。

【讨论】:

  • 如何更改为 py 3
  • @user133745:你不能使用 Canopy。安装不同的 Python 3 发行版。
  • 如果不支持 Python 3,为什么在 py3compat.pyc 文件中的 def execfile() 不支持 Python 3?
  • @J.F.Sebastian: 那是IPython compatibility layer;它有助于保持代码库在 Python 2 和 3 之间的兼容性。
  • @user133745:你可以试试Anaconda;它还附带 iPython,但支持 Python 3 和 Python 2。
猜你喜欢
  • 2018-03-11
  • 2020-01-09
  • 2015-04-13
  • 1970-01-01
  • 2011-05-06
  • 2012-11-14
  • 2019-02-11
  • 2014-04-28
  • 1970-01-01
相关资源
最近更新 更多