Python入门(四)之 循环语句---解析式

作者:PyQuant
博客https://blog.csdn.net/qq_33499889
慕课https://mooc1-2.chaoxing.com/course/207443619.html


点赞、关注再看,养成良好习惯
Life is short, U need Python
初学Python,快来点我吧
在这里插入图片描述



1. 循环语句

Python 循环语句有 while 和 for。

1.1 while 循环语句

  • while…
a = 10
b = 20

while a < b:
    print(a)
    a += 5
10
15
  • while…else…
a = 10
b = 20

while a < b:
    print(a)
    a += 5
else:
    print('python')
10
15
python
  • while…if…else…
a = 10
b = 20

while a > b:
    print(a)
if a < b:
    print(b)
else:
    print('python')
20
  • while + break 语句(跳出 while 循环)
a = 10
b = 20

while a < b:
    print(b)
    a += 5
else:
    print('python')
20
20
python
a = 10
b = 20

while a < b:
    print(b)
    a += 5
    break
else:
    print('python')
20
  • while + continue 语句
a = 10
b = 20

while a < b:
    print(b)
    a += 5
    print('python')
20
python
20
python
a = 10
b = 20

while a < b:
    print(b)
    a += 5
    continue
    print('python')
20
20

1.2 for 循环语句

  • for…
for i in range(1,5):
    print(i * 10)
10
20
30
40
  • for…if…else…
for i in range(1,5):
    if i < 3:
        print(str(i) + 'Python')
    else:
        print(str(i) + 'Java')
1Python
2Python
3Java
4Java
  • for + break 语句
for i in range(1,5):
    print(i)
    break
    print('python')
1
for i in range(1,5):
    print(i)
    if i > 2:
        break
   
1
2
3
  • for + continue 语句
for i in range(1,5):
    print(i)
    continue
    print('java')
1
2
3
4
for i in range(1,5):
    print(i)
    if i < 3:
        continue
    print('java')
1
2
3
java
4
java
  • while + for + continue + break 语句
a = 10
b = 20

while a < b:
    for i in range(3):
        print(a + i)
        if i < 2:
            continue
        else:
            print('python')
    a += 5
    break
print(a + b)
10
11
12
python
35

2. 解析式

解析式(analytic expression)又称推导式(comprehensions),是Python的一种独有特性。

  • 列表解析式
lst = [1,2,3,4,5,6,7,8]

even_numbers = [lst[i] for i in range(len(lst)) if lst[i] % 2 == 0]

print(even_numbers)
[2, 4, 6, 8]
  • 字典解析式
d = {key:value**2 for key,value in [('a',10),('b',20)]}

print(d)
{'a': 100, 'b': 400}
  • 集合解析式
s = {x for x in 'hello python' if x not in 'hello world'}

print(s)
{'y', 'p', 'n', 't'}
  • 元组生成器(迭代式)
lst = [1, 2, 3, 4]

t = (i for i in lst if i > 2)

print(t)
<generator object <genexpr> at 0x0000022239DB7308>
print(list(t))
[3, 4]
lst = [1, 2, 3, 4]
t = (i for i in lst if i > 2)

for i in t:
    print(i)
3
4
lst = [1, 2, 3, 4]
t = (i for i in lst if i > 2)

print(next(t))
print(next(t))
print(next(t))
3
4
---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-21-2959ae7a56f8> in <module>()
      4 print(next(t))
      5 print(next(t))
----> 6 print(next(t))
StopIteration: 

  • 写作不易,切勿白剽
  • 博友们的点赞关注就是对博主坚持写作的最大鼓励
  • 持续更新,未完待续…

上一篇Python入门(三)之 字符串–列表–元组–字典–集合
下一篇Python入门(五)之 Python函数

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章