What is the output of this code snippet?
words = ['cat', 'mouse'] for w in words: print(len(w))
The world around us is built around repetition. The sun goes up every morning and after winter comes spring. As coders, we model and simulate the real world and create our own worlds with our own laws and repetitions. Suppose you want to program a web server that repeats forever the following behavior. Wait for a user request and answer it. How can you program the web server to repeat this behavior thousands of times?
The naive approach is to put the sequence of steps into the source code itself. In other words, copy and paste the sequence of steps thousands of times. Yet, repeated code is redundant, hard to read, debug, and maintain. As programmers, we should avoid redundant code at all costs.
The Python for loop statement is a way out of redundant code. You write code only once and put it into different contexts. In other words, the loop variable (e.g. w in the puzzle) accounts for the different contexts of loop executions. For example, in the puzzle word w is first ‘cat’ and second ‘mouse’.
Among the ingredients that make a programming language powerful are control flow statements. The Python for loop is one such control flow statement.
It repeats execution of the code body for all elements in a sequence. Then, it iterates over all sequence elements in the order of the sequence. In the puzzle, we print out the length of each word in the sequence.
Are you a master coder?
Test your skills now!