Explain a For-In LoopDescribing how a for-in loop works was difficult and I repeatedly ran into attendees who just couldn't quite grok it. A Python for-in loop looks like:
for word in wordlist: print word
That would loop through the wordlist data structure, which we'll say is a list (similar to an array in other languages), printing each term to the screen. Simple, right? But it's actually pretty weird, because in the above example what exactly is word? It's a local variable that gets a new value each time through the loop. If for-in loops for lists didn't exist in Python, you might implement them like so:
i = 0 while i < len( wordlist ): # being super explicit here word = wordlist[ i ] print word i = i + 1
len( wordlist )here returns the length of the wordlist list, for non-Python people. Otherwise, I assume the syntax is straightforward for anyone who knows a little code. The biggest disadvantage to this implementation is you end up with two variables in the scope—
word—neither of which is useful after the loop has run.
I'm not sure my explicit for-in loop is more clear to a new programmer, but it's my conceptual model. Students struggled with understanding the for variable's name; where does
wordcome from? In the lecture, Becky Yoose used this example:
for fruit in pies: print fruit
The reaction from attendees seemed to be "since pies is a list of different fruits, the variable name has to be 'fruit' here." As if Python was somehow doing natural language processing to figure out a good descriptive term of an individual item in a thematic list. It's a weird thing to grasp conceptually, perhaps the crux being you're getting a variable without any assignment statement. That's a nice convenience for programmers coming from other languages but it obscures what's going on for learners.
Python's conveniences, like
But the setup process wasn't an issue for the preconference. We held a help session the night before and only two people came; one of them already had Python installed and on the Windows path, they just needed confirmation that they'd done it right. A number of factors contributed to the ease of setup: many attendees had Macs which typically come with a 2.6.x or 2.7.x version of Python, the Boston Python Workshop docs are great and cross-platform, and a fair portion of attendees were advanced computer users. So with an easy setup, Python (or Ruby) is a sensible choice for a first language.