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]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值