Section 4.8 👩💻 Naming Variables in For Loops
We’ve mentioned before about carefully choosing your variable names. Though the names you choose aren’t meaningful to the program, they can be to you. When we choose names for variables in for loops, the more understandable they are to us, the easier it will be to use them. Here are some tips to make your for loops more readable for yourself and anyone else who may read your programs:
- Use singular nouns for the iterator variable, which is also called the loop variable (things like “song”, “book”, “post”, “letter”, “word”).
- Use plural nouns for the sequence variable (i.e., name you list something like “songs”, “books”, “posts”, “letters”, “words”).
While these two tips won’t always apply, they are general best practices when it comes to choosing variable names. Below we have an example!
Since we can’t see the contents of x right now - this might be the case if we have a long program - then these names would make the program hard to understand. Let’s compare this to a program that does the same thing, but uses better names.
The code below is used to initialize the two lists used above: x and genres. Click to open.
You have attempted of activities on this page.