开发者

python print done after while

I am new to python: my aim is to print a done statement after while loop but it gives me syntax error

>>> i=0
>>> while i < 10:
...  print i
...  i=i+1
...
... print "done"
  File "<stdin>", line 6
    print "done"
        ^
SyntaxError: invalid syntax

 

<?php

$i=0;
while($i<10)
{
echo "$i \n";
}
echo "done";
?>

I am trying to replicate the same php program in python

i tried

>>> i=0
>>> while i < 10:
...  print i
...  i=i+1
... print "done"
  File "<stdin>", line 4
    print "done"
        ^
SyntaxError: invalid syntax

still it fails cant we use a print开发者_开发知识库 after end or do we have to wait for the while to finish and do the print


First-level blocks in the REPL must be terminated by a completely empty line.

>>> i=0
>>> while i < 10:
...   print i
...   i=i+1
... 
0
1
2
3
4
5
6
7
8
9
>>> print "done"
done


Just get rid of that space on your empty line after the while loop. The space makes the interpreter think that the loop is continuing.


You can do this with the while..else control structure. The code would then be:

>>> i = 1
>>> while i < 10:
...     i = i + 1
... else:
...     print 'done'
...
...
done
>>>

Though this would typically be written in python as:

>>> for i in range(10):
...     pass
... else:
...     print 'done'
...
...
done
>>>


If you see '>>>', you are not writing a program. You are using an interpreter. You feed it one statement at a time.

If you want to write a program, save it in a plain text file with a .py extension. You should be able to run this by double-clicking it (although it will not pause at the end, so you might just see the command window flash), or by supplying the file's name as an argument to python at the command line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜