0

guys, I'm learning Python recently, I got a problem when I write some simple codes in Python Shell(command in Terminal in Linux) and in a file:

in Python Shell:

>>> 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

if print(sum(firstn(1000000))), the print will be a SyntaxError too

But when I put the codes into a file, and execute it, it is totally OK, no SyntaxError, I don't know why. Is there anyone who can explain this? PS: The code is from https://wiki.python.org/moin/Generators

2 Answers 2

4

In interactive mode, put blank line to end the block.

>>> 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, the code make a cyclic reference in the following line:

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, the first line "In interactive mode, put blank line to end the block." is very useful to me, I should define every block in different part in the shell.But the rest of your answer makes confused, I didn't get the TypeError like your(BTW, I'm using Python 3.2),
@codychan, See this line: nums.append(nums). This add nums to nums itself!
@codychan I would recommend always adding a blank line after a function definition. It says somewhere in PEP8 that you should do that, and anyway it will make it easier for your to copy and paste into your interactive python sessions.
0

It worked fine for me when I copied directly from the Python docs. When I tried adding a space before the last line (sum_of_first_n) I received that same syntax error message. Most likely a copy paste error. Try copying to a text editor to check for spaces and then paste into terminal.

1 Comment

Thanks anyway, the space is not the problem, the lack of a blank line is, just like @falsetru answered. BTW, I didn't copy and paste the codes into my terminal, I typed them by hands, so there's no "a space before last line" issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.