Python保留字とキーワードの使い方


Python保留字とキーワードの使い方の詳細
python 3のまとめを学ぶ
Python 3ドキュメントの詳細:https://docs.python.org/3/reference/lexical_analysis.html#keywords
概念:予約字はpython言語で予め保持された識別子であり、プログラムには特定の用途があり、変数名、関数名として使用できない.文字の大文字と小文字の機密性を保持し、False、True、Noneを除く
pythonキーワードリストの取得
import keyword
print(keyword.kwlist)

--- Python 3.6 Console Output ---
['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']

--- Python 3.7 Console Output --- 
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

予約語の詳細
1、TrueとFalse
ブール型変数の値、Trueが真、Falseが偽
is_1 = True
is_2 = False

2、if、elif、else
判定文、条件分岐文
if score < 60:
	print(“   ”)
elif score < 80:
	print("    ")
else:
	print("  ")

3、in
リストにあるかどうかを判断する
2 in [1,2,3,4]

4、del
delete変数を削除するか、リストの要素を削除します.
a = "hello, world!"
b = hello

del b 
print(a)   #  hello, world!

list = [1, 2, 3, 4, 5, 6]
del list[1]
print(list)   # [1, 3, 4, 5, 6]

5、forwhileとbreakcontinue
ループ文の作成
continue続行、すなわちループをスキップし、直ちに次のループを実行
breakループ文の終了
for i in [1,2,3,4,5,6]:
	if  i == 2:
		continue
	if i == 4:
		break 
	print(i)    # 1 3        i==2,   i==4        

6、and orとnot
または非
そしてFalseがあり、結果はFalseです.
orまたは1つのFalseのみ、結果はTrue
not非
7、def returnとyield
defは関数を定義し、returnは関数から返すために使用され、値を持つことができます.
yieldジェネレータ関数にyieldが使用されると、解釈器は関数をジェネレータとして解釈します.
# def   return   
def feb(max):
	a, b = 1, 1
	while a < max:
		yield a
		a, b = b, a + b

for i in feb(20):
	print(i)     #             
# yield   
def foo():
    print("hello world!")
    return 

def square(num):
    return num*num 

foo()  # hello world! 
print(square(5))  # 25

8、class定義クラス
オブジェクト向けプログラミング
class Cat:
    def __init__(self, name):
        self.__name = name

    def miaow(self):
        print(self.__name + " is miaow....")


cat = Cat("tom")
cat.miaow()

9、from、import、as
from … import … as …
から...インポート...別名を指定します...
10、assert
ブール値を計算して、断言が成立して、プログラムは引き続き実行して、断言が失敗して、実行を停止して、AssertErrorと指定した文字列を印刷します
デバッグに多く使用されます.if判断文の代わりに使用できないことに注意してください.
x = 24
assert x % 2 == 1, "ok"

Traceback (most recent call last):
  File "C:********/study.py", line 2, in 
    assert x % 2 == 1, "ok"
AssertionError: ok

11、is
変数が同じオブジェクトを参照するかどうかを判断する
オブジェクトidが同じか否かを判断する
12、pass
空の文、プレースホルダ、プログラムの完全性を維持
x = 10
if x > 8:
    print("ok")
else:
    pass 

13、None
Noneは変数が制御であることを示します
14、try、except、finally
tryは異常をキャプチャするために使用され、異常が発生した場合はexceptの後の文を実行し、異常がなければelseの後の文を実行する
例外の有無にかかわらずfinallyの後の文を実行します
x = 2
try:
    print("Let's try 0 / 0")
    x = x / 0
except:
    print("one exception")
else:
    print("no exception")
finally:
    print("this sentence must be read")

15、withとas
with文が入力されると、オブジェクトの__が実行されます.enter__()メソッドで、このメソッドが返す値はasが指定したターゲットに付与されます.with文が終了すると、オブジェクトの__が実行されます.exit__()メソッドは、異常が発生しているかどうかにかかわらず、クリーンアップ作業を行います.
16、global
pythonの後の変数がグローバル変数であることを定義して通知し、新しいローカル変数を定義しないでください.
x = 6
def local_x():
	x = 7
	print("x in func = " + str(x))

local_x()   # x in func = 7
print("global x = " + str(x))   # global x = 6

print("")

def global_x():
	global x    #   x     
	x = 7
	print("x in func = " + str(x))

global_x()  # x in func = 7
print("global x = " + str(x))  # global x = 7

17、lambda
式の定義、匿名関数
a = lambda x,y: x+y
print(a(1,2))  # 3 

18、async、await
廖雪峰先生の説明を参照すると、generatorをcoroutineタイプとマークし、coroutine内部でyield fromで別のcoroutineを呼び出して非同期操作を実現することができます.
非同期IOを簡略化し、よりよく識別するために、Python 3.5から新しい構文asyncawaitが導入され、coroutineのコードをより簡潔に読みやすくすることができます.asyncawaitはcoroutineの新しい構文です.新しい構文を使用するには、2つのステップで簡単に置き換える必要があります.
  • @asyncio.coroutineasyncに置き換えた.
  • yield fromawaitに置き換えます.