Python Question?

techi3

In Runtime
Messages
119
Why does this work? How does it associate "letter" with an individual letter? I've been reading "Think Python" and Google searching but am still having trouble understanding programming.

for letter in 'Python':
print 'Current Letter :', letter

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
 

Celegorm

Site Team
Staff member
Messages
11,741
Location
USA
The for-in loop is kind of a special (and powerful) version of the for-loop.

Normally, to do what that does you'd need to do something like the following:

Code:
String python = "Python"
String[] letters = python.toArray()

for (int i = 0; i < letters.size(); i++) {
    print letters[i]
}

What the the for-in loop does is breaks the string into an irritable array for you so you don't need to worry about out of bounds errors or manually creating more temporary variables than needed. It's all done in the background for you after the code is compiled.
 
Top