条件判断
- 比较操作符:
>
<
=
>=
<=
-
True
False
- 数值:
0
为假,非零为真 - 序列(字符串,列表等):空为假,非空为真
-
in
not in
-
and
or
not
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()
-
range()
用于生成一系列有序的数字; - 接受3个参数,分别是
start
end
step
-
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
-
continue
用于跳过某一次循环 -
break
用于终止循环 - 在循环未被
break
终止的情况下,当for
循环遍历完或while
循环的条件为假时,执行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
网友评论