Python 代码在 2.7 中编译,而不是在 3.2 中编译

标签 python python-3.x

我现在正在做 Google 的 python 教程,并且正在完成文件 list1.py。

我应该用我自己的代码填充 def match_ends(words) 部分,它应该计算输入 words 中有多少单词同时具有:超过 2 个字母且开头和结尾字母相同。

当我运行我使用 python 2.7 编写的代码时,它运行良好。但是当我使用 3.2 运行它时,它没有。此外,当我在 IDLE 3.2 中输入它说有问题的行时,有问题的行运行正常。

这是 list1.py:

def match_ends(words):
  count = 0
  for x in words:
    if len(x) >= 2 and x[0] == x[len(x)-1]:
        count += 1
  return count
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
def main():
  print('match_ends')
  test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
  test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
  test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
if __name__ == '__main__':
  main()

当我在 Python 2.7 的命令行中运行它时,它工作正常,输出:

 OK  got: 3 expected: 3
 OK  got: 2 expected: 2
 OK  got: 1 expected: 1

当我在 Python 3.2 的命令行中运行它时,它不起作用,输出:

  File "D:\Projects\Programming\Python\Tutorials\Google Python Class\google-python-exercises\basic\list1.py", line 26
    if len(x) >= 2 and x[0] == x[len(x)-1]:
                                          ^
TabError: inconsistent use of tabs and spaces in indentation

最后,当我使用 IDLE 3.2 时,我得到:

>>> def match_ends(words):
    count = 0
    for x in words:
        if len(x) >= 2 and x[0] == x[len(x)-1]:
            count += 1
    return count

>>> match_ends(["heh", "pork", "veal", "sodas"])
2

我是 Python 的新手,大多数生成的错误都花了一些时间来弄清楚,但我已经在这个错误上停留了一段时间。我想不通。为什么它不能在 Python 3.2 中工作,并且只能在我执行命令行版本时使用?我该如何解决这个问题?

最佳答案

您可能混合了制表符和空格字符,这在 Python 3.x 中不再被允许。 您可以通过在文本编辑器中显示空白字符来解决此问题。

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

引自:http://docs.python.org/py3k/reference/lexical_analysis.html#indentation

关于Python 代码在 2.7 中编译,而不是在 3.2 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657733/

相关文章:

python - imp.get_suffixes() 已弃用,如何修复?

python - 如何从 JSON 中删除键和值

python - 如果 Keras 结果不可重复,比较模型和选择超参数的最佳实践是什么?

javascript - 无法通过静态 URL 包含外部 javascript 文件

python - 当授予监控帐户权限时,有没有办法使用 python 查询计费使用情况?

python - python中类型转换函数的时间复杂度是多少?

python - 在 pandas 数据框中过滤和分配值

Python3, flake8 - 文件类型注释

python - 管道 ("bitwise OR") 调用 fcntl.lockf()

python-3.x - Gunicorn 没有自动启动