SV: [Tutor] Why different behaviours?

Danny Kohn danny.kohn@systematik.se
Fri, 26 Oct 2001 22:11:48 +0200


Thanks everybody for the answers. It works now.

Danny, the problem is not the print formatting in gerenal although it =
might have been. What bugs me is why the print statement in the first =
example is not printing out one character per line (as there is no comma =
last!). It seems to me that there is something more fundamental I have =
not grasped yet. Why is there a difference between when a string is =
printed and when it is used in a for loop as index?

In Basic for example I can be certain that what I see when I print is =
what I get internaly. Here it seems that I get one thing when I print it =
and another thing when I try to use it internally in code. Either the =
result of f.readline is a character and so each character should print =
out on a separate line or it is not a character and so it should be used =
as a line in a for loop.

/Danny

| -----Ursprungligt meddelande-----
| Fran: tutor-admin@python.org [mailto:tutor-admin@python.org]For Danny
| Yoo
| Skickat: den 26 oktober 2001 17:59

| > Why does:
| > import string, sys
| >=20
| f=3Dopen('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon
| .txt', 'r')
| > line =3D f.readline()
| > print line
| >=20
| > and:
| >=20
| > import string, sys
| >=20
| f=3Dopen('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon
| .txt', 'r')
| > for line in f.readline():
| > 	print line
|=20
|=20
| The variable naming in your second version might be obscuring an =
issue:
|=20
| > for line in f.readline():
| > 	print line
|=20
| In this case, we're asking Python to do a for loop along every thing =
in an
| f.readline().  In that case, we're going to go along every character =
of
| that read line, so the loop might be better written as:
|=20
| ##
| for character in f.readline():
|     print line
| ###
|=20
|=20
| Also, Python's "print" statement will automatically put a newline, =
unless
| we place a trailing comma.  We can see this from this interpreter =
session:
|=20
| ###
| >>> print "abc"
| abc
| >>> for letter in "abc":
| ...     print letter
| ...
| a
| b
| c
| >>> for letter in "abc":
| ...     print letter,
| ...
| a b c
| ###