0
votes

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

4
Sounds like Python 3.x complaining that print should be called as a function, e.g. print("done") - samplebias
Then why would print i work? - pajton
I thought that was the problem too but i tested the code in 2.6 and received the same error. I think it is because you are trying to execute multiple statements at the same time within the shell. I tested this with an if statement and got the same error. - josh-fuggle

4 Answers

1
votes

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.

4
votes

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

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.

0
votes

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