[Tutor] Newbie

Andreas Kostyrka andreas at kostyrka.org
Thu Jul 24 12:48:07 CEST 2008


On Wednesday 23 July 2008 22:04:57 Alan Gauld wrote:
> ""Simón A. Ruiz"" <sruiz at canterburyschool.org> wrote
>
> > If what you expected was something like:
> >
> > Hello World!
> > Here are ten numbers from 0 to 9
> > 0 1 2 3 4 5 6 7 8 9 Goodbye World!
> >
> > Then you want that final print statement to not be included in your
> > for loop block; i.e., unindent it:
>
> And if you wanted the Goodbye on a separate line add a
> newline character('\n') in front of the text:
>
> for i in range(10):
>      print i,
> print "\nGoodbye World!"
>
> You now have at least 3 options to pick from :-)

One another *g*

print " ".join(str(x) for x in range(10))
print "Goodbye World!"

Which has the "benefit" of not printing a space after the 9.

explanations:

str(x) converts the integers to strings.
str(x) for x in range(10) is basically a generator that 
generates "0", "1", ..., "9"

" ".join(expr) joins the strings given by expr by " ".

It's basically a very useful idiom when you need to generate
seperators without outputing the seperator at the end.

In other languages, you often have a loop like this:

for elem in list:
    print elem
    if is_not_last_element:
        print seperator

That is most often best solved in Python by using the " ".join(values) idiom.

Andreas
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/a56ced14/attachment.pgp>


More information about the Tutor mailing list