条件与循环
条件语句
语法
if condition_1:
statement_1
elif condition_2:
statement_2
...
elif condition_i:
statement_i
else:
statement_n
整个条件语句是顺序执行的,如果遇到一个条件满足,如condition_i满足时,在执行完statement_i后,便会退出整个if、elif、else条件语句,而不会继续向下执行
实例
- 表示y=|x|这个函数
if x < 0:
y = -x
else:
y = x
省略判断条件的常见用法
注:在实际写代码时,除了boolean类型的数据,条件判断最好时显性的
循环语句
循环本质上就是遍历集合中的元素
实例
- 遍历列表中的所有元素并打印输出
l = [1, 2, 3, 4]
for item in l:
print(item)
1
2
3
4
Python中数据结构只要是可迭代的(iterable),如列表、集合等等,都可以通过这种方式遍历
for item in <iterable>:
...
字典比较特殊。字典本身只是键可迭代的,如果要遍历它的值或者是键值对,需要通过其内置的函数values()或者items()实现。
values()返回字典的值的集合,items()返回键值对的集合
d = {'name': 'jasom', 'dob': '2000-01-01', 'gender': 'male'}
for k in d:
print(k)
name
dob
gender
for v in d.values(): # 遍历字典的值
print(v)
jason
2000-01-01
male
for k, v in d.items(): # 遍历字典的键值对
print('key: {}, values: {}'.format(k, v))
key: name, value: jason
key: dob, value: 2000-01-01
key: gender, value: male
通过range()这个函数,拿到索引,再去遍历访问集合中的元素
l = [1 ,2, 3, 4, 5, 6, 7]
for index in range(0, len(l)):
if index < 5:
print(l[index])
1
2
3
4
5
同时需要索引和元素时,可以通过内置函数enumerate()
l = [1, 2, 3, 4, 5, 6, 7]
for index, item in enumerate(l):
if index < 5:
print(item)
1
2
3
4
5
循环语句中的continue和break
continue就是让程序跳过当前这层循环,继续执行下面的循环;
break则是指完全跳出所在的整个循环体;
实例
- 给定两个字典,分别是产品名称到价格的映射,和产品名称到列表的映射。找出价格小于1000,并且颜色不是红色的所有产品名称和颜色的组合
# name_price: 产品名称(str)到价格(int)的映射字典
# name_color: 产品名字(str)到颜色(list of str)的映射字典
for name, price in name_price.items():
if price < 1000:
if name in name_color:
for color in name_color[name]:
if color != 'red':
print('name: {}, color: {}'.format(name, color))
else:
print('name: {}, color: {}'.format(name, 'None'))
使用continue的代码
# name_price: 产品名称(str)到价格(int)的映射字典
# name_color: 产品名字(str)到颜色(list of str)的映射字典
for name, price in name_price.items():
if price >= 1000:
continue
if name not in name_color:
print('name: {}, color: {}'.format(name, 'None'))
continue
for color in name_color[name]:
if color == 'red':
continue
print('name: {}, color: {}'.format(name, color))
对于while循环,原理是一样的。当condition满足时,一直重复循环内部的操作,直到condition不再满足,跳出循环体。
while condition:
...
两种循环使用场景的区别
如果只是遍历一个已知的集合,找出满足条件的元素,并进行响应的操作,那么使用fot循环更加简洁。
如果需要在满足条件前,不停地重复某些操作,并且没有特定的集合需要去遍历,那么一般则会使用while循环
实例
- 交互式问答系统,用户输入文字,系统根据内容做出相应的回答
while True:
try:
text = input('Please enter your questions, enter 'q' to exit')
if text == 'q':
break
...
...
print(resonse)
except Eeception as err:
print('Encountered error: [}'.format(err))
break
for循环和while循环的效率问题
i = 0
while i < 1000000:
i += 1
等价
for i in range(0, 100000):
pass
range()函数是直接由C语言写的,调用它速度非常快。而’i+=1’需要通过Python的解释器间接调用底层的C语言。
显然for循环的效率更胜一筹。
条件与循环的复用
条件与循环并作一行的操作
expression1 if condition else expression2 for item in iterable
将这个表达式分解
for item in iterable:
if condition:
expression1
else:
expression2
实例
- 将文件中逐行读取的一个完整语句,按逗号分割单词,去掉首位的空字符,并过滤掉长度小于5的单词,最后返回由单词组成的列表
text = 'Today, is, Sunday'
text_list = [s.strip() for s in text.split(',') if len(s.strip()) > 5]
print(text_list)
['Today', 'Sunday']