4.13. SummaryΒΆ

In this chapter we took a big step toward writing useful Python programs. We covered the following topics:

  1. Branching constructions (if-then constructions), which allow a program to do different things, depending on the outcome of a test.

  2. Booleans. This is a new Python type, consisting of two elements True and False. One of these two objects is returned by operators like in and < in tests like x in C and x < y. More importantly, many Python objects can be used as if they were Booleans and thus can legally occur in if tests. Most container objects behave as if they were True, but empty containers ([], {}, '', and ()) behave as if they were False. Most numbers behave as if they were True, but zero in all types (0, 0.0, and 0j) behaves as if it was False.

  3. Sets. A new type of container whichg is updatable but not sequenced, useful for storing collections with no duplication allowed.

  4. Loops. The for and while 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.

  5. 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.

  6. 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.