:
>>> def firstn(n):
... num, nums = 0, []
... while num < n:
... nums.append(nums)
... num += 1
... return nums
... sum_of_first_n = sum(firstn(1000000))
File "<stdin>", Line7
sum_of_firstn_n = sum(firstn(1000000))
^
SyntaxError: invalid syntax
如果是print(sum(firstn(1000000))),那么打印也会是一个SyntaxError
但是当我将代码放入文件并执行它时,它完全没问题,没有SyntaxError,我不知道为什么。有没有人可以解释这个? PS:代码来自https://wiki.python.org/moin/Generators
答案 0 :(得分:4)
在交互模式下,输入空行以结束块。
>>> def firstn(n):
... num, nums = 0, []
... while num < n:
... nums.append(nums)
... num += 1
... return nums
...
>>> sum_of_first_n = sum(firstn(1000000))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
BTW,代码在以下行中生成循环引用:
nums.append(nums)
>>> def firstn(n):
... num, nums = 0, []
... while num < n:
... nums.append(num) # <--
... num += 1
... return nums
...
>>> sum_of_first_n = sum(firstn(1000000))
>>> sum_of_first_n
499999500000L
答案 1 :(得分:0)
当我直接从Python文档中复制时,它对我来说很好。当我尝试在最后一行(sum_of_first_n)之前添加空格时,我收到了相同的语法错误消息。很可能是复制粘贴错误。尝试复制到文本编辑器以检查空格,然后粘贴到终端。