Python语句简介

Python语句简介

重访Python程序结构

深入学习:

  1. 程序由模块组成
  2. 模块包含语句
  3. 语句包含表达式
  4. 表达式建立并处理对象

Python语法实质上是由语句和表达式组成。首先给出表来整体理解Python内的语句。

语句 角色 例子
赋值 创建引用值 a, b, c = 'wk', 'name', 'age'
调用 执行函数 log.write("spam, ham")
打印调用 打印对象 print('The killer', joke)
if/elif/else 选择动作 if "python" in text: print(text)
for/else 序列迭代 for x in mylist: print(x)
while/else 一般循环 while X > U: print('hello')
pass 空占位符 while True: pass
break 循环退出 while True:
if test(): break
continue 循环继续 while True:
if skip(): continue
def 函数和方法 def f(a, b, c=1, *d): print(a+b+c+d[0])
return 函数return def f(a, b, c=1, *d): return a+b+c+d[0]
yield 生成器函数 def gen(n):
for i in n: yield i*2
global 命名空间 x = 'old'
def function():
golbal x, y; x = 'new'
nonlocal Namespaces def outer():
x = 'old'
def function():
nolocal x; x = 'new'
import 模块访问 import sys
from 属性访问 from sys import stdin
class 创建对象 class Subclass(Superclass):
staticData = []
def method(self): pass
try/except/finally 捕捉异常 try:
action()
except:
print('action error')
raise 触发异常 raise EndSearch(location)
assert 调试检查 assert X > Y, 'X too small'
with/as 上下文 with open('data') as myfile: process(myfile)
del 删除应用 del data[k]; del data[i:j]; del obj.attr; del variable

简要解释

  • 从技术上讲,printPython 3中不是保留字,也不是语句,而是一个内置的函数调用,所以写成:print()
  • yield实际上是一个表达式,而不是一条语句,同时也是一个保留字;
  • Python 2中,nonlocal不可用;
  • Python 2中,print是一条语句;
  • 在Python 2中,try/excepttry/finally语句合并了;

Python语法模型

  • 一行的结束就是终止该行语句(没有分号);
  • 嵌套语句是代码块并且与实际的缩进相对应(没有大括号);
  • Python所有的复合语句都有相同的一般形式,首行以冒号结束,下一行嵌套的代码按照缩进的格式书写;
    如:
1
2
Header line:
Nested statement block

特殊情况

虽然Python中都是一行一条语句,可是也有一些特殊情况书写:

  1. 一行含有多条

    a = 1; b = 2; print(a + b)

  2. 一条语句跨越多行代码

    1
    2
    3
    mlist = [111,
    222,
    333]
    • 不仅是方括号,”()” “{}”内的代码,也被视作一行。
  3. 代码块特殊实例,代码块的复合语句只有一句的时候

    if x > y: print(x)

以上是本章基础内容,接下来给出一个基础程序代码:

1
2
3
4
5
6
7
8
9
while True:
reply = input('enter text:')
if reply == 'stop': break
elif not reply.isdigit(): print('error input!' * 7)
else:
num = int(reply)
if num < 20: print('low')
else: print(num ** 2)
print('bye')