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:

  1. Use singular nouns for the iterator variable, which is also called the loop variable (things like “song”, “book”, “post”, “letter”, “word”).

  2. 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.

Here what we expect is much more clear, even if we didn’t see how genres was initialized!

The code below was used to initialize x and genres so you’re free to look at it but you don’t need to run it!

You have attempted of activities on this page