[Tutor] for loop

W W srilyk at gmail.com
Fri Apr 17 04:01:48 CEST 2009

On Thu, Apr 16, 2009 at 3:45 PM, mbikinyi brat <mbikinyi_brat at yahoo.com>wrote:

> Dear ALL,
> I am a beginner in python and I just copied the code in blue below and
> execute and had the result in green. Then I thought *letter* should be a
> special word in python. Then I now replace letter whith *chic*  and yet
> the same results is obtained. I cannot reconcile them. Can someone explained
> to me please?

I think your confusion lies in how python for loops work.

"Python" in this case is a string. You could replace it with "Spam"
"Knights" or "Ni", if you so desire. A string is an iterable - in other
words, you can iterate over it automatically.

With a language like C++ you would write something like this:

string foo = "python";
for(int x = 0; x < foo.size; x++){
    cout << foo.at(x) << endl;

to iterate over the string. Python takes care of that for you with any
iterable type (list, set, etc.)

for item in [1, 2, 3]:
    print item

for letter in "word":
    print word

for foobar in (1, 0, 234, 'hello', 'foo'):
    print foobar

It all works the same. It's rather useful :)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090416/cd8d9b62/attachment.htm>

More information about the Tutor mailing list