[英]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. 我是“如何像计算机科学家一样思考”的第6章“迭代/循环遍历”的初学者。
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. 您似乎在shell中运行(
<stdin>
暗示),并且在shell中,相同的代码段对我也不起作用(在Ubuntu上为python 2.7.2)。
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: 也就是说,为了终止预期的
while
子句,您必须输入一个空行:
>>> 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: 另一个解决方法是在
if 1
子句中输入要执行的内容:
>>> 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. ...我认为这是
print
语句末尾的串行逗号。 As said before, if you're using Python 3, it turns into a function (eg print(2*i)
). 如前所述,如果您使用的是Python 3,它将变成一个函数(例如
print(2*i)
)。
EDIT: After looking a bit closer, it would be easier to simply remove the extra print
. 编辑:稍微靠近一点后,只需除去多余的
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.
如果要打印水平表,则在初始打印语句后添加换行符没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.