Statements and Syntax
Python syntax is designed to be simple. There are a few rules; we'll look at some of the interesting statements in the language as a way to understand those rules. Concrete examples can help clarify the language's syntax.
We'll cover some basics of creating script files first. Then we'll move on to looking at some of the more commonly-used statements. Python only has about 20 or so different kinds of imperative statements in the language. We've already looked at two kinds of statements in Chapter 1, Numbers, Strings, and Tuples, the assignment statement and the expression statement.
When we write something like this:
>>> print("hello world")
hello world
We're actually executing a statement that contains only the evaluation of a function, print()
. This kind of statement—where we evaluate a function or a method of an object—is common.
The other kind of statement we've already seen is the assignment statement. Python has many variations on this theme. Most of the time, we're assigning a single value to a single variable. Sometimes, however, we might be assigning two variables at the same time, like this:
quotient, remainder = divmod(355, 113)
These recipes will look at some of the more common of the complex statements, including if
, while
, for
, try
, and with
. We'll touch on a few of the simpler statements as we go, like break
and raise
.
In this chapter, we'll look at the following recipes:
- Writing Python script and module files - syntax basics
- Writing long lines of code
- Including descriptions and documentation
- Better RST markup in
docstrings
- Designing complex
if...elif
chains - Saving intermediate results with the
:=
"walrus" - Avoiding a potential problem with
break
statements - Leveraging exception matching rules
- Avoiding a potential problem with an
except:
clause - Concealing an exception root cause
- Managing a context using the
with
statement
We'll start by looking at the big picture – scripts and modules – and then we'll move down into details of individual statements. New with Python 3.8 is the assignment operator, sometimes called the "walrus" operator. We'll move into exception handling and context management as more advanced recipes in this section.