--- title: 【Python】 斷言 assert date: 2020-02-27 modified: 2020-02-27 disqus: cynthiahackmd categories: - "程式設計 › 程式語言與架構" tags: - "Python" --- {%hackmd @CynthiaChuang/Github-Page-Theme %} <br> 在 Python 中 assert 陳述句長這樣: ```python assert <test>, <message> ``` 我會跟你說我記錄這個的原因是因為我老是拼錯嗎? <!--more--> ## 斷言(Assertion) 所謂的斷言,指的就是==斷定程式進行到特定時間、地點時其變數的狀態==,像是變數大小、變數狀態、是否為空值...等。我個人還滿喜歡用斷言,與其讓程式在執行時 crash,再一行一行去追 log,倒不我先檢查變數,錯誤時直接中斷運作,...至少 log 也好看一點 XD <br> 下面這段程式碼用來檢查選擇的預訓練模型是否支援。因為 `selected` 不在 `SUPPORT_MODELS` 中,所以會中斷運作,並跳出我寫好的錯誤訊息。 ```python= SUPPORT_MODELS = ['ResNet50', 'Xception', 'VGG16', "DenseNet121", "InceptionV3", "InceptionResNetV2", "MobileNetV2"] selected = 'VGG19' assert selected in SUPPORT_MODELS, \ "{} isn't supported Please select a model of the following: {}".format(self.apps, ",".join(SUPPORT_MODELS)) ``` ## 參考資料 1. 林信良。[使用 assert](https://openhome.cc/Gossip/Python/Assert.html) 。檢自 語言技術:Python Gossip (2020-02-27)。 <br><br> > **本文作者**: 辛西亞.Cynthia > **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/Python-Assert) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/Python-Assert) > **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!
×
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