【问题标题】:Moving from Python 3 to Python 2从 Python 3 迁移到 Python 2
【发布时间】:2013-10-14 20:02:13
【问题描述】:
print('10 -> 2 [bd], 2 -> 10 [db]')
answ=input('select db or bd : ')

if  answ == "db":
a=input('enter a digit')
x=int(a)
list1 = []

while (x):
    x%2
    x//2

    if x==0:
        break

我开始在 python 3.2 上创建它,但后来我不得不继续使用 python 2.7.5,我收到以下错误消息:

Traceback (most recent call last):
  File "C:\Users\<file path>", line 3, in <module>
    answ=input('select db or bd : ')
  File "<string>", line 1, in <module>
NameError: name 'db' is not defined
>>> 

我真的不知道帽子是怎么回事,在 python 3.2 上工作得很好(对不起我的英语不好)。

【问题讨论】:

  • 用 raw_inputs 替换输入,并在等号之间添加空格,工作。感谢您的支持:)

标签: python string list if-statement compiler-errors


【解决方案1】:

你需要使用raw_input:

answ=raw_input('select db or bd : ')

Python 2.x 中的input 将输入评估为真正的 Python 代码。

另外,只是一个提示:这两行:

x%2
x//2

什么都不做。也许你的意思是:

x %= 2
x //= 2

【讨论】:

  • 更多信息this question有详细信息。
  • @MarcelChyra - 嗯,这很奇怪。我在 Python 2.7.5 中运行了代码,完全没有收到错误。
【解决方案2】:

在 python 2 中,等同于 input 被称为 raw_input

所以第 2 行应该是 answ=raw_input('select db or bd : ')

http://docs.python.org/2/library/functions.html#raw_input

【讨论】:

    猜你喜欢
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多