Python --条件和循环

目录

1, 条件判断

1-1, if语句

1-2, else语句

1-3, elif语句

1-4, 条件表达式

2, 循环

2-1, while循环

2-2, for循环

2-3, break语句

2-4, continue语句

3, else语句与for和while结合使用

4, 迭代器

4-1, 迭代器使用

5, 迭代文件对象

6, 迭代可变对象

7, 列表解析式

8, 生成器表达式


1, 条件判断

通过if语句来实现条件判断

1-1, if语句

当if语句表达式为真执行其后面的代码块

# if表达式为真, 执行if后的代码块
In [1]: x = 1
In [2]: if x > 0:
   ...:     print('大于0')
   ...:
大于0

1-2, else语句

当if语句表达式为假执行else后的代码块

else语句同层级的if语句匹配

最多只有一个else语句

# if表达式为假,执行else后的代码块
In [3]: x = 1
In [4]: if x > 2:
   ...:     print('大于2')
   ...: else:
   ...:     print('小于2')
   ...:
小于2

1-3, elif语句

当一个判断中存在多种情况时,可通过elif语句进行判断, 执行elif后表达式为真的代码块

In [5]: score = 85

In [6]: if 90<=score<=100:
   ...:     print("A")
   ...: elif 80<=score<90:
   ...:     print("B")
   ...: elif 70<=score<80:
   ...:     print("C")
   ...: elif 60<=score<70:
   ...:     print("D")
   ...: else:
   ...:     print("E")
   ...:
B

# 通过字典获取的方式,比条件判断和循环的性能更好
In [14]: mgs = dict(create='create_item', delete='delete item', update='update item')

In [15]: mgs
Out[15]: {'create': 'create_item', 'delete': 'delete item', 'update': 'update item'}

In [16]: action = mgs.get('create', 'opps')

In [17]: action
Out[17]: 'create_item'

1-4, 条件表达式

通过result = result1 if expression else result2, 表达式expression结果为真,则返回result1, 否则返回result2

In [18]: x = 1
In [19]: y = 2

In [20]: greater = x if x > y else y

In [21]: greater
Out[21]: 2

2, 循环

2-1, while循环

while中的表达式为真时,执行其后的代码块, 直到表达式为假,则跳出循环

In [30]: while i < 5:
    ...:     print('i:', i)
    ...:     i += 1
    ...:
i: 0
i: 1
i: 2
i: 3
i: 4

2-2, for循环

对象为序列时, 遍历输出序列的所有元素

对象为迭代器时, 自动调用迭代器的next()方法,直到捕获到StopInteration,从而结束循环

# 迭代字符串,是按字符逐个进行迭代的
In [31]: for char in 'abcde':
    ...:     print(char)
    ...:
a
b
c
d
e

# 迭代非字符串序列或迭代器时是按元素为单位进行迭代的
In [33]: for name in ['aa', 'bb', 'cc', 'dd']:
    ...:     print(name)
    ...:
aa
bb
cc
dd

2-3, break语句

break与循环结合使用时,表示跳出循环, 执行循环后的语句部分

# break语句的作用:跳出循环
In [46]: while count <= 9:
    ...:     if count == 5:  # 因为count=5时,跳出了循环,所以结果输出到4
    ...:         break
    ...:     print(count)
    ...:     count += 1
    ...:
    ...:
0
1
2
3
4

# for循环中break使用,跳出循环
In [67]: for i in range(10):
    ...:     if i == 5:
    ...:         break
    ...:     print(i)
    ...:
0
1
2
3
4

2-4, continue语句

continue与循环结合使用时,表示跳出本次循环,继续下次循环

# continue:结束本次循环,继续下次循环
In [65]: count = 0

In [66]: while count <= 9:
    ...:     count += 1
    ...:     if count == 5:  # 因为 count=5时,结束了本次循环,所以没有输出结果为的情况
    ...:         continue
    ...:
    ...:     print(count)
    ...:
1
2
3
4
6
7
8
9
10

# for循环中的continue使用,跳出本次循环
In [68]: for i in range(10):
    ...:     if i == 5:
    ...:         continue
    ...:     print(i)
    ...:
0
1
2
3
4
6
7
8
9

3, else语句与for和while结合使用

在循环中使用时,else语句只在整个循环完成后才会执行,若循环中有break跳出循环,则else语句不会执行

与for和while处于同层级

# 因为整个for循环都执行完成,中途没有跳出循环,所以执行了else语句
In [69]: for i in range(10):
    ...:     if i == 10:
    ...:         break
    ...: else:
    ...:     print("循环正常结束,没有中途跳出")
    ...:
循环正常结束,没有中途跳出

# 应为i=5时,跳出了循环,所以没有执行else语句
In [78]: for i in range(10):
    ...:     if i == 5:
    ...:         break
    ...: else:
    ...:     print("循环正常结束,没有中途跳出")
    ...:

In [79]:

# 因为整个while循环都执行完成,中途没有跳出循环,所以执行了else语句
In [77]: while i <= 10:
    ...:     i += 1
    ...:     if i == 12:
    ...:         break
    ...: else:
    ...:     print("循环正常结束,没有中途跳出")
    ...:
    ...:
循环正常结束,没有中途跳出

# 应为i=10时,跳出了循环,所以没有执行else语句
In [79]: while i <= 10:
    ...:     i += 1
    ...:     if i == 10:
    ...:         break
    ...: else:
    ...:     print("循环正常结束,没有中途跳出")
    ...:
    ...:

4, 迭代器

迭代器是一个有next()方法的对象,调用迭代器的next()方法,就可以获取到该对象的下个元素

序列对象可以通过iter()方法转换为迭代器,能够带来性能上的增强

迭代器不能后向后移动,也不能回到开始,若要重新迭代,只能重新创建一个迭代器

迭代器迭代完成后,会抛出一个StopIteration的错误,表示迭代完成

for循环自动调用迭代器的next()方法,遍历所有元素,并捕获StopIteration错误

4-1, 迭代器使用

通过iter(seq), 可以将一个序列对象转换为迭代器, 从而提高性能

In [5]: my_tuple
Out[5]: (123, 'xyz', 45.67)

# 元组转换为迭代器
In [3]: i = iter(my_tuple)

In [6]: i
Out[6]: <tuple_iterator at 0x26e9a154970>

# 通过next()方法访问迭代器的元素
In [7]: next(i)
Out[7]: 123

In [8]: next(i)
Out[8]: 'xyz'

In [9]: next(i)
Out[9]: 45.67

# StopIteration表示迭代完成
In [10]: next(i)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-10-a883b34d6d8a> in <module>
----> 1 next(i)

# 通过for循环迭代迭代器
# for循环会自动调用迭代器的next()方法,遍历所有元素,并捕获StopIteration错误
In [19]: my_iter = iter(my_tuple)

In [20]: for i in my_iter:
    ...:     print(i)
    ...:
123
xyz
45.67

5, 迭代文件对象

在通过for循环迭代文件对象时,这里的文件对象相当于f.readlines()

In [27]: f = open(path)

# 文件句柄使用for循环时,会自动调用f.readlines()方法,读取文件所有的行
In [28]: for eachline in f:
    ...:     print(eachline.strip('\n'))
    ...:
    ...:
line1
line2
line3
line4
line5

# 这里回显为空,是因为f已经被迭代完了
In [29]: for eachline in f:
    ...:     print(eachline.strip('\n'))
    ...:
    ...:

6, 迭代可变对象

在迭代可变对象时, 不要修改可变对象的值

In [46]: my_dict = dict(a=1, b=2, c=3, d=4)

# 注意:这里会报错,是因为迭代器只是记录你当前的位置,若修改了可变对象,则当前的位置就变化了
# 所以在迭代可变对象时,不要对齐进行修改
In [48]: for k in my_dict:
    ...:     if k == 'a':
    ...:         del my_dict[k]
    ...:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-48-61482be3e24f> in <module>
----> 1 for k in my_dict:
      2     if k == 'a':
      3         del my_dict[k]
      4

RuntimeError: dictionary changed size during iteration

7, 列表解析式

通过[expr for iter_var in iterable]方式, 可动态创建列表, expr应用于序列(iterable)的每个元素,最后的结果为该表达式值产生的列表

In [51]: [i for i in range(10)]
Out[51]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [52]: [i for i in range(10) if i % 2 ==0]
Out[52]: [0, 2, 4, 6, 8]

8, 生成器表达式

生成器是一个特定的函数, 允许返回一个值,然后"暂停"执行的代码,稍后恢复

生成器表达式不是创建整个列表,它是返回一个生成器生成器是每次计算一个值,然后把该值yield出来

生成器表达式是用来延迟计算,所以更节省内存

# 函数中包含yield,表示该函数是一个生成器
In [72]: def rows():
    ...:     yield 1
    ...:     yield 2
    ...:     yield 3
    ...:     yield 5

In [54]: def cols():
    ...:     yield 56
    ...:     yield 2
    ...:     yield 1
    ...:


# 通过中括号生成生成器
# 注意for使用中是调用的生成器, 而不是写的函数名字
x_product_pairs = ((x, y) for x in rows() for y in cols())


In [84]: for x in x_product_pairs:
    ...:     print(x)
    ...:
(1, 56)
(1, 2)
(1, 1)
(2, 56)
(2, 2)
(2, 1)
(3, 56)
(3, 2)
(3, 1)
(5, 56)
(5, 2)
(5, 1)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值