Python -- 控制流

2018-03-07  本文已影响0人  liaozb1996

条件判断

IF

if 语句可以包含多个 elif 和一个可选的 else

>>> number = 24
>>>
>>> if number > 0:
...     print('Position')
... elif number < 0:
...     print('Negative')
... else:
...     print('Zero')
...
Position

while

>>> i = 0
>>>
>>> while i < 3:
...     print(i)
...     i += 1
...
0
1
2
>>>

for

python 中的 for 循环用于遍历序列

>>> numbers = [1, 2, 3]
>>>
>>> for num in numbers:
...     print(num)
...
1
2
3
>>>

常和 for 搭配的函数 range()

>>> list(range(5))
[0, 1, 2, 3, 4]
>>>
>>> list(range(0, 5))
[0, 1, 2, 3, 4]
>>>
>>> list(range(1, 10, 2))
[1, 3, 5, 7, 9]

循环中的 continue break else

>>> numbers = [1, 2, 3]
>>>
>>> for num in numbers:
...     print(num)
... else:
...     print('The End')
...
1
2
3
The End
>>>

pass

pass 用于占位,可用于先勾勒出程序的结构,稍后再把代码填充完整

class MyClass:
    pass

def func():
    pass
上一篇下一篇

猜你喜欢

热点阅读