4.13. Summary¶
In this chapter we took a big step toward writing useful Python programs. We covered the following topics:
Branching constructions (
if-then
constructions), 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
True
andFalse
. One of these two objects is returned by operators likein
and<
in tests likex in C
and x < y. More importantly, many Python objects can be used as if they were Booleans and thus can legally occur inif
tests. 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
for
andwhile
loops are Python’s basic iteration constructions.for
loops are most useful for iterating through the contents of any container, executing the same basic operation on each member;while
continue 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.