DS4UX (Spring 2016)/Working within loops

From CommunityData

So far in this course, we've covered assigning to variables, addition, conditionals, and the special .append() function associated with lists. Solving the Day 2 Coding Challenges with the Wordplay project is going to require you use not only use these things but put them together.

I wanted to show you some concrete examples of this. These aren't answers but hopefully you'll see how they might be applied to make progress on some of the coding challenges.

Here's an example of a counter variable I can use to count the number of names in a list that should be familiar from lecture:

 names = ["graham", "eric", "terry g", "terry j", "john", "michael"]
 
 counter = 0
 for name in names:
     counter = counter + 1

 print(counter)

Sure enough, that code will print "6" which is the number of things in the list.

The only thing might seem new here is the line with counter in it twice. All we're doing in that line is just adding 1 to the variable counter and then replacing the old value with the new, slightly bigger, version.

Of course, instead of that counter and for loop, we could have just used len(names) and it would have done the same thing! This is powerful because loops are much more flexible and combined with other things we've learned. For example, lets say I wanted to count the number of names that start with the letter "t". I could combine that counter above with an if statement that checks if the "0th" item in each name (i.e., the first letter) to see if it's "t" like this:

 names = ["graham", "eric", "terry g", "terry j", "john", "michael"]
 
 counter = 0
 for name in names:
     if name[0] == "t":
         counter = counter + 1

 print(counter)

Now, this program will print out "2" (the number of names that start with "t") instead of "4".

Python can do anything from within a loop! For example, lets say I wanted to create a new list (I'll call the variable t_names) that contains only those names that start with "m". In this case, the code I'll write is going to similar to what we've already seen except I will replace the counter with an empty list ([]) and I'll append things to that list every time there's a match from within a loop. Here's an example:

 names = ["graham", "eric", "terry g", "terry j", "john", "michael"]
 
 t_names = []
 for name in names:
     if name[0] == "t":
         t_names.append(name)

 print(t_names)

Run these little programs in Python (or save them to files and run them in your terminal) and try to use the concepts to make some progress on the Day 2 Coding Challenges.