concept guard in category python

appears as: guard
Tiny Python Projects: Learn coding and testing with puzzles and games

This is an excerpt from Manning's book Tiny Python Projects: Learn coding and testing with puzzles and games.

$ ./rhymer.py RDNZL
Cannot rhyme "RDNZL"

The task of finding the initial consonants is made significantly easier with regexes.

In this program, you will

  • Learn to write and use regular expressions
  • Use a guard with a list comprehension
  • Explore the similarities of list comprehension with a guard to the filter() function
  • Entertain ideas of “truthiness” when evaluating Python types in a Boolean context


Figure 14.2 The for loop (top) can be written as a list comprehension (bottom). This list comprehension includes a guard so that only consonants are selected, which is like the if statement at the top.

For the purposes of this program, the “stem” of a word is the part after any initial consonants, which I define using a list comprehension with a guard to take only the letters that are not vowels:

>>> vowels = 'aeiou'
>>> consonants = ''.join([c for c in string.ascii_lowercase if c not in vowels])

Throughout the chapters, I have shown how a list comprehension is a concise way to generate a list and is preferable to using a for loop to append to an existing list. Here we have added an if statement to only include some characters if they are not vowels. This is called a guard statement, and only those elements that evaluate as “truthy” will be included in the resulting list.

We’ve looked at map() several times now and talked about how it is a higher-order function (HOF) because it takes another function as the first argument and will apply it to all the elements from some iterable (something that can be iterated, like a list). Here I’d like to introduce another HOF called filter(), which also takes a function and an iterable (see figure 14.12). As with the list comprehension with the guard, only those elements that return a “truthy” value from the function are allowed in the resulting list.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest