官术网_书友最值得收藏!

  • Modern Python Cookbook
  • Steven F. Lott
  • 360字
  • 2021-06-11 18:49:11

2 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 = pmod(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 inpidual 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.

主站蜘蛛池模板: 漠河县| 吉林省| 烟台市| 玉门市| 容城县| 长海县| 青州市| 来安县| 天长市| 永济市| 友谊县| 沧州市| 朔州市| 万荣县| 民乐县| 南京市| 临潭县| 瑞昌市| 苏州市| 广元市| 峨边| 德昌县| 南昌县| 呼和浩特市| 垣曲县| 通城县| 衡水市| 陇川县| 北宁市| 那坡县| 灵山县| 北京市| 大田县| 团风县| 扎囊县| 嘉荫县| 宁乡县| 怀集县| 阿克苏市| 乌拉特中旗| 仙居县|