第5章 条件、循环及其他语句
程序员文章站
2022-06-15 18:43:14
...
5.1 再谈print和import
5.1.1 打印多个参数
>>> a = 'Hello'
>>> b = ' world!'
>>> print(a,b)
Hello world!
>>>
5.1.2 导入时重命名
>>> import math as foobat
>>> foobat.sqrt(4)
2.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
>>>
5.2 赋值魔法
5.2.1 序列解包
>>> x,y,z = 1,2,3
>>> print(x,y,z)
1 2 3
>>> a,b,*c = 1,2,3,4
>>> print(a,b,c)
1 2 [3, 4]
>>>
5.2.2 链式赋值
x = y = somefunction()
5.2.3 增强赋值
>>> x = 2
>>> x += 1
>>> x *= 2
>>> x
6
>>>
5.3 代码块:缩进的乐趣
5.4 条件和条件语句
5.4.1 这正是布尔值的用武之地
>>> bool('abc')
True
>>> bool(1)
True
>>> bool('')
False
>>> bool(0)
False
>>>
5.4.2 有条件执行和if语句
5.4.3 else字句
name = input('what is your name?')
if name.endswith('peter'):
print('good person')
else:
print('bad guy')
name = input('again?')
status = 'good person' if name.endswith('peter') else 'bad guy'
print(status)
5.4.4 elif字句
name = input('what is your name?')
if name.endswith('peter'):
print('good person')
elif name.endswith('a'):
print('test elif')
else:
print('bad guy')
5.4.5 代码库嵌套
5.4.6 更复杂的条件
5.4.7 断言
让程序在错误条件出现时立即崩溃好过以后再崩溃。
>>> age = -1
>>> assert age > 0, "bigger zero"
Traceback (most recent call last):
File "<pyshell#218>", line 1, in <module>
assert age > 0, "bigger zero"
AssertionError: bigger zero
>>>
5.5 循环
5.5.1 while循环
5.5.2 for循环
# while循环
x = 1
while x < 10:
print(x)
x += 1
# for 循环
words = ["a",'b', 'c']
for word in words:
print(word)
5.5.3 迭代字典
d = {'x' : '1', 'y' : 2, 'z' : [1,2,4]}
for key in d:
print(key, " to ", d[key])
for key,value in d.items():
print(key,' to ',value)
5.5.4 一些迭代工具
1 并行迭代
>>> a = [1,2,3]
>>> b = ['a', 'b', 'c']
>>> for av,bv in zip(a,b):
print(av,' ', bv)
1 a
2 b
3 c
>>>
2 迭代时获得索引
a = ['aaa','bbb']
for index,s in enumerate(a):
print(s,index)
if 'aa' in s:
a[index] = 'ccc'
print(a)
5.5.5 跳出循环
break
continue
5.5.6 循环中的else字句
5.6 简单推导
列表推导是一种从其他列表创建列表的方式。
>>> [x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x * x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>>
5.7 三人行
5.7.1 什么都不做
pass
5.7.2 使用del删除
>>> x = 1
>>> x
1
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#251>", line 1, in <module>
x
NameError: name 'x' is not defined
>>>
5.7.3 使用exec和eval执行字符串及计算结果
1 exec
将字符串当作代码执行
>>> exec("print('Hello,world!')")
Hello,world!
>>>
2 eval
eval用字符串表示表达式的值,并返回结果(exec什么都不返回,因为它本身是条语句)
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 2+3
5
>>>
5.8 小结
上一篇: Introduction to Activities
下一篇: 第五章 条件,循环和其他语句