user719852
user719852

Reputation: 131

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

Upvotes: 0

Views: 7988

Answers (4)

Schlueter
Schlueter

Reputation: 4029

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

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61478

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.

Upvotes: 0

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

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.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

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

Upvotes: 4

Related Questions