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 1 of 4 activities on this page.