简体   繁体   中英

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.

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.

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

...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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM