Jason HJH.
Jason HJH.

Reputation: 169

Syntax Error While Learning Loops

I'm a beginner into Chapter 6 of "How to Think like a Computer Scientist", section on Iteration/While Loops.

In the book, a syntax for 2-dimensional table is as follow:

i=1
while i <= 6:
  print 2*i, '   ', 
  i=i+1 
print

However, doing so results in a syntax error. The terminal gave

File "<stdin>", line 4
    print
        ^
SyntaxError: invalid syntax

I know that the second print statement is unnecessary and removing it would correct the error; however, a line in the later section of the book explains that the second print statement is intended to create a new line after printing a horizontal table. Hence I believe it could be a typo error. I tried several variations but still could not come to a solution.

Upvotes: 0

Views: 944

Answers (3)

glglgl
glglgl

Reputation: 91059

You do not mention if you have the stuff in a file or if you enter it manually.

In the latter case, your terminal looks like

>>> i=1
>>> while i <= 6:
...   print 2*i, '   ',
...   i=i+1
... print
  File "<stdin>", line 4
    print
        ^
SyntaxError: invalid syntax

That is, in order to terminate the intended while clause, you have to enter an empty line:

>>> i=1
>>> while i <= 6:
...   print 2*i, '   ',
...   i=i+1
...

And here execution already happens.

Another workaround could be to enter the stuff you wantto execute in an if 1 clause:

>>> i=1
>>> if 1:
...  while i <= 6:
...   print 2*i, '   ',
...   i=i+1
...  print
...
2     4     6     8     10     12
>>>

Upvotes: 3

keppla
keppla

Reputation: 1751

It seems to be a problem with the shell

When executing the snippet you posted as a file, it runs. You seem to run in in a shell (<stdin> hints that), and in the shell, the same snippet does not work for me (python 2.7.2 on Ubuntu) too.

Upvotes: 3

Makoto
Makoto

Reputation: 106450

...I think that it's that serial comma at the end of the print statement. As said before, if you're using Python 3, it turns into a function (e.g. print(2*i)).

EDIT: After looking a bit closer, it would be easier to simply remove the extra print. It isn't necessary. If you're printing out a horizontal table, there's nothing wrong with appending a newline character to your initial print statement.

Upvotes: 1

Related Questions