>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
False
|
True
|
None
|
|
|
|
and
|
as
|
assert
|
break
|
class
|
continue
|
def
|
del
|
elif
|
else
|
except
|
finally
|
for
|
from
|
global
|
if
|
import
|
in
|
is
|
lambda
|
nonlocal
|
not
|
or
|
pass
|
raise
|
return
|
try
|
while
|
with
|
yield
|
with open('test.txt') as f:
f.read()
‘’'
with語句的目的是簡化try/finally模式,用於保證一段代碼運行完畢之後能夠執行某項操作,即便代碼由於**異常、return語句或者sys.exit()**調用而中止。
‘’’
#try/finally模式下的文件操作模式:
try: f = open('test.txt’)
f.read()
finally:
f.close()
‘’’
對比於with…as語句來說,try/finally模式顯得過於複雜,通常大家習慣於使用更加簡潔的with…as語句
‘''
6、assert
import time
'''
break 關鍵字示例
'''
while True:
time.sleep(2) # 睡眠2秒
print('運行到這裏:第一層循環')
while True:
print('運行到這裏:第二層循環')
break
### 備註:break會跳出第二層循環,就是說break關鍵字只會停止最內一層循環,外層的循環是不受影響的。
8、class
# 定義一個類
class People:
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def Name(self):
print("姓名:", self.name)
def Sex(self):
print("性別:", self.sex)
def Age(self):
print("年齡:", self.age)
pp = People('lily', 'female', 25)
pp.Name()
pp.Sex()
pp.Age()
9、continue
while True:
time.sleep(2) # 睡眠2秒
print('運行到這裏:第一層循環')
i = 0
while True:
time.sleep(2) # 睡眠2秒
print('運行到這裏:第二層循環')
if i > 5:
print('i大於5的時候,不執行本次循環的後面的代碼,但是不會跳出本層循環')
continue
i = i + 1
10、def
if 表達式:
Statement
# 表達式爲真(True),那麼就執行Statement.如果表達式爲假(False),那麼就不執行Statement。
13、else
判斷語句,對應if語句
if 表達式:
Statement1
else
Statement2
# 表達式爲真(True),那麼就執行Statement1.如果表達式爲假(False),那麼就執行Statement2。
14、elif
if 表達式1:
Statement1
elif 表達式2:
Statement2
else
Statement3
# 表達式1爲真(True),那麼就執行Statement1.如果表達式1爲假(False),那麼就判斷表達式2是不是爲真,如果表達式2爲真,就執行Statement2,如果表達式2也是假,那麼就執行Statement3。
15、try
try:
Statement1
except expression as identifier:
Statement2
else:
Statement3
finally:
Statement4
# 執行Statement1發生異常expression,那麼執行Statement2
# 如果發生的異常不是expression,而是其他類型異常,那麼就執行Statement3
# finally是不管異常發不發生,都會執行Statement4
18、for
for i in range(5):
print('i = ', i)
19、from