# 在Python中使用yield ## yield 的目的 * 為了節省記憶體的使用 ## 實作原理 * 相當於return,只回傳一次的值,傳完之後便將之遺忘,而下次迴圈會由yield的下一行開始執行 ## 範例一(搭配next) code ```python = def test(): print("start...") while True: y = yield 10 print("this time yield: ", y) t = test() print(next(t)) print("-"*30) print(next(t)) ``` output ``` start... 10 ------------------------------ this time yield: None 10 ``` 由下方這句,可以明確看到當y已傳至next()後,便忘記y值為何 ``` this time yield: None ``` ## 範例二(搭配send) 若是使用send()函數,則將send之值存起來再繼續跑 code ```python = def test(): print("start...") while True: y = yield 10 print("this time yield: ", y) t = test() print(next(t)) print("-"*30) print(t.send(87)) ``` output ``` start... 10 ------------------------------ this time yield: 87 10 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up