作者: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:
- 寫作不易,切勿白剽
- 博友們的點贊和關注就是對博主堅持寫作的最大鼓勵
- 持續更新,未完待續…