While loop - print several times but on 1 line.

Diez B. Roggisch deets at nospam.web.de
Thu Jan 26 05:16:35 EST 2006


Danny wrote:

> Hello there.
> 
> I'm creating a little text changer in Python. In the program there is a
> while loop. The problem is that a while loop will have 1 print statement
>   and it will loop until it gets to the end of the text.
> Example:
> 
> num = 5 // Set num to 5
> while num >= 1: // loop 5 times.
> print """text"""
> num = num-1
> // end.

Don't use while for that, this is considered unpythonix. Use a for-loop with
xrange instead. If you need the nums in that order, use xrange with a
negative step:

Use sys.stdout.write:

import sys

for i in xrange(num, 0, -1):
    sys.stdout.write("text")


Diez



More information about the Python-list mailing list