python简明教程_05
python编程语言简明教程,翻译自以下仓库:
Python-Lectures
原仓库是一系列的jupyter notebook,可以直接在jupyter环境下运行程序示例。我添加了中文注释,并改为了兼容python3
控制流程
If
if some_condition:
algorithm
x = 12
if x >10:
print("Hello")
Hello
If-else
if some_condition:
algorithm
else:
algorithm
x = 12
if x > 10:
print("hello")
else:
print("world")
hello
if-elif
if some_condition:
algorithm
elif some_condition:
algorithm
else:
algorithm
x = 10
y = 12
if x > y:
print("x>y")
elif x < y:
print("x<y")
else:
print("x=y")
x<y
if 流程可以嵌套其他 if 流程
x = 10
y = 12
if x > y:
print("x>y")
elif x < y:
print("x<y")
if x==10:
print("x=10")
else:
print("invalid")
else:
print("x=y")
x<y
x=10
循环
For
for variable in something:
algorithm
for i in range(5):
print(i)
0
1
2
3
4
也可以在一个多维的列表上循环:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list1 in list_of_lists:
print(list1)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
循环也可以嵌套:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list1 in list_of_lists:
for x in list1:
print(x)
1
2
3
4
5
6
7
8
9
While
while some_condition:
algorithm
i = 1
while i < 3:
print(i ** 2)
i = i+1
print('Bye')
1
4
Bye
Break
break可以用来打破循环:
for i in range(100):
print(i)
if i>=7:
break ### 满足条件时终止这个for循环
0
1
2
3
4
5
6
7
Continue
continue用来在条件达成后继续此循环:
for i in range(10):
if i>4:
print("The end.")
continue
elif i<7:
print(i)
0
1
2
3
4
The end.
The end.
The end.
The end.
The end.
列表解析
列表解析说的是借助循环,Python可以用一行代码生成指定规则的列表。比如如果想要生成以27的倍数组成的列表:
res = []
for i in range(1,11):
x = 27*i
res.append(x)
print(res)
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]
列表解析的方法也可以达成这个目的:
[27*x for x in range(1,11)]
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]
判断条件也可以嵌套:
[27*x for x in range(1,20) if x<=10]
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]
更多条件:
[27*z for i in range(50) if i==27 for z in range(1,11)]
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]
[27*z for i in range(50) if i<7 for z in range(1,11)]
[27,
54,
81,
108,
135,
162,
189,
216,
243,
270,
27,
54,
81,
108,
135,
162,
189,
216,
243,
270,
27,
54,
81,
108,
135,
162,
189,
216,
243,
270,
27,
54,
81,
108,
135,
162,
189,
216,
243,
270,
27,
54,
81,
108,
135,
162,
189,
216,
243,
270,
27,
54,
81,
108,
135,
162,
189,
216,
243,
270,
27,
54,
81,
108,
135,
162,
189,
216,
243,
270]
上一篇: neo4j-(1)-CQL