4.13. Summary¶
In this chapter we took a big step toward writing useful Python programs. We covered the following topics:
Branching constructions (
if-thenconstructions), which allow a program to do different things, depending on the outcome of a test.Booleans. This is a new Python type, consisting of two elements
TrueandFalse. One of these two objects is returned by operators likeinand<in tests likex in Cand x < y. More importantly, many Python objects can be used as if they were Booleans and thus can legally occur iniftests. Most container objects behave as if they wereTrue, but empty containers ([], {}, '', and()) behave as if they wereFalse. Most numbers behave as if they wereTrue, but zero in all types (0, 0.0, and0j) behaves as if it wasFalse.Sets. A new type of container whichg is updatable but not sequenced, useful for storing collections with no duplication allowed.
Loops. The
forandwhileloops are Python’s basic iteration constructions.forloops are most useful for iterating through the contents of any container, executing the same basic operation on each member;whilecontinue executing the same block of instructions until some terminating condition is met.List comprehensions are convenient and readable oPython idioms for writing loops that build lists from some operation iterated over the elements of a container:
L = [Op(x) for x in L]
A list comprehension can always be rewritten as a loop, usually with with more lines. Not every loop can be written as a list comprehension.
Functions are useful ways of encapsuling reusable blocks of code. Once you’ve identified a block of code that you want to make into a function, you need to choose a name for the function and the parameters.
