In most programming languages, a "for" loop is used to execute a set ofstatements a certain number of times. Unlike a "while" loop, whichcontinues to run for so long as the specified conditional expressionevaluates as true, a "for" loop comes with a specific limit on the numberof times it can iterate. Python's "for" loop conforms to this basic requirement; however, as withmost things in Python, there's a twist in the tail. A Python "for" loop isdesigned only to iterate over built-in "sequence objects" like strings andlists, and is structured like this: Or, in English, "take each element of the sequence sequence_obj, place itin the variable temp_var, and execute the indented code block on temp_var". An example might help to make this clearer: In this case, I've first initialized a list containing four elements. Next,I've used a "for" loop to iterate through the list; on each successiveiteration, one element of the list is assigned to the temporary variable"myhero" and then printed to the console via a print() call. Once all theelements of the list have been processed, the loop is automaticallyterminated. You can use a "for" loop with any "sequence object" - this next exampledoes something similar with a string.
blog comments powered by Disqus |