5、条件、循环和其他语句

赋值魔法包括:

序列解包:将多个值的序列解开,然后放在变量的序列中。

>>> x,y,z=1,2,3
>>> x,y=y,x
>>> x,y,z
(2, 1, 3)

链式赋值:

>>> x=y=1
>>> x,y
(1, 1)

增量赋值

>>> x=2
>>> x+=1
>>> x*=2
>>> x
6

布尔表达式中,False None 0 “” () [] {}被解释器看做假,其他的一些被解释为真。

条件语句:if else elif(else if)

Python中比较运算符是可以连接使用的,如

>>> 1<2<3
True

布尔运算符:and or not

断言:if语句的近亲,它的工作进入如下(伪代码)

If not condition

Crash program

关键字是 assert,在程序中置入检查点,条件后可添加解释字符

>>> age=-1
>>> assert 0<age<100, 'error age'
Traceback (most recent call last):
File "<pyshell#110>", line 1, in <module>
assert 0<age<100, 'error age'
AssertionError: error age

循环的实现:while语句非常灵活,可以在指定条件下重复执行一个代码块

>>> x=1
>>> while x<3:
    x+=1
    print(x)
2
3

for循环,对集合中的每个元素都执行一个代码块

>>> for num in x:
    print(num)
1
2
3
>>> for num in range(3):
    print(num)
0
1
2

并行迭代:zip函数可以用于任意多的序列

>>> for x,y in zip(range(5),range(10000)):
    print(x,'-',y)
0 - 0
1 - 1
2 - 2
3 - 3
4 - 4

编号迭代:替换所有包含‘xxx’的子字符串

for index,string in enumerate(strings):
    if ‘xxx’ in string
        string[index]=’newsub’

循环中的break语句,它只在没有调用break时执行:

>>> for num in range(1,3):
    if num==4:
        break
else:
    print('no break')
no break

列表推导式:利用其它列表创建新的列表

>>> [x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]

Python中使用缩进(Tab)表示语句块,相同缩进的语句属于同一语句块。

原文地址:https://www.cnblogs.com/houkai/p/3478756.html