5.20 è®©ä½ æ™•å¤´è½¬å‘çš„ else 用法 ============================= |image0| if else 用法å¯ä»¥è¯´æœ€åŸºç¡€çš„è¯æ³•è¡¨è¾¾å¼ä¹‹ä¸€ï¼Œä½†æ˜¯ä»Šå¤©ä¸æ˜¯è®²è¿™ä¸ªçš„。 if else 早已烂大街,但我相信ä»ç„¶æœ‰å¾ˆå¤šäººéƒ½ä¸æ›¾è§è¿‡ for else å’Œ try else 的用法。为什么说它曾让我晕头转å‘ï¼Œå› ä¸ºå®ƒä¸åƒ if else 那么直白,éžé»‘å³ç™½ï¼Œè„‘åç»å¸¸è¦æƒ³ä¸€ä¸‹æ‰èƒ½æ‰å应过æ¥ä»£ç 怎么走。 å…ˆæ¥è¯´è¯´ï¼Œfor … else … .. code:: python def check_item(source_list, target): for item in source_list: if item == target: print("Exists!") break else: print("Does not exist") 在往下看之å‰ï¼Œä½ å¯ä»¥æ€è€ƒä¸€ä¸‹ï¼Œä»€ä¹ˆæƒ…况下æ‰ä¼šèµ° else。是循环被 break,还是没有break? ç»™å‡ ä¸ªä¾‹åï¼Œä½ ä½“ä¼šä¸€ä¸‹ã€‚ .. code:: python check_item(["apple", "huawei", "oppo"], "oppo") # Exists! check_item(["apple", "huawei", "oppo"], "vivo") # Does not exist å¯ä»¥çœ‹å‡ºï¼Œæ²¡æœ‰è¢« break 的程åºæ‰ä¼šæ£å¸¸èµ°elseæµç¨‹ã€‚ å†æ¥çœ‹çœ‹ï¼Œtry else 用法。 .. code:: python def test_try_else(attr1 = None): try: if attr1: pass else: raise except: print("Exception occurred...") else: print("No Exception occurred...") åŒæ ·æ¥å‡ 个例å。当ä¸ä¼ å‚数时,就抛出异常。 .. code:: python test_try_else() # Exception occurred... test_try_else("ming") # No Exception occurred... å¯ä»¥çœ‹å‡ºï¼Œæ²¡æœ‰ try 里é¢çš„代ç å—没有抛出异常的,会æ£å¸¸èµ°else。 总结一下,for else å’Œ try else 相åŒï¼Œåªè¦ä»£ç æ£å¸¸èµ°ä¸‹åŽ»ä¸è¢« break,ä¸æŠ›å‡ºå¼‚常,就å¯ä»¥èµ°else。 |image1| .. |image0| image:: http://image.iswbm.com/20200804124133.png .. |image1| image:: http://image.iswbm.com/20200607174235.png