? ? Python中的條件語句與我之前學(xué)過的C,C++很相像,在Python里用 and 代替了&&(與運算符),用or代替了||(或運算符),而其他比較運算符如>,<,=,>=,<=,==,!=的用法和意義與C一致。在使用Python的if語句時,要注意冒號和縮進。?最簡單的if語句為
if 條件測試:
? ? 要執(zhí)行的內(nèi)容
如:
a=5
if a>3:
? ? print("a is larger than 3")
if else語句與此類似,如
a=5
if a>3:
? ? print("a is larger than 3")
else:
? ? print("a is smaller than 3")
? ? 除此以外,還有語句if-elif-else,當(dāng)它遇到通過了的條件測試時,會跳過其他余下的測試,對于一對一的判斷效率很高。elif比較像C中的else if。當(dāng)需要同時判斷多種情況時,就要使用一系列的if,而不是elif。
? ? 還可以用if語句處理列表,這里參考書中的練習(xí)題舉例。
例1:創(chuàng)建包含五個用戶名的列表,當(dāng)用戶名為“admin”,輸出“Hello admin”,否則輸出“Hello Eric”。當(dāng)列表為空時,輸出“Empty”
User_Names = ['A','B','C','D','admin']
if User_Names:
?? ?for User_Name in User_Names:
?? ??? ?if User_Name == 'admin':
?? ??? ??? ?print("Hello admin")
?? ??? ?else:
?? ??? ??? ?print("Hello Eric")
else:
?? ?print("Empty")
這里通過if User_Names判斷列表是否為空。
例2:創(chuàng)建兩個列表,一個為當(dāng)前已有的用戶名列表current_users,一個為新創(chuàng)建的用戶名列表new_users,檢查新列表中的用戶名是否被使用,在比較時不區(qū)分大小寫。
current_users = ['Alan','Bob','Clark','David','Eric','Frank']
new_users = ['Gaea','henry','alan','ClarK']
current_lower_users=[]
for current_user in current_users:
?? ?if current_user:
?? ??? ?current_lower_users.append(current_user.lower())
?? ??? ?
if new_users:
?? ?for new_user in new_users:
?? ??? ?if new_user.lower() in current_lower_users:
?? ??? ??? ?print(new_user+" has been enabled.")
?? ??? ?else:
?? ??? ??? ?print(new_user+" enable")
這里我使用一個新的列表current_lower_users用來保存current_users列表中的全小寫元素。最終運行結(jié)果為:
Gaea enable
henry enable
alan has been enabled.
ClarK has been enabled.
可以達到預(yù)期的目的。不過感覺這種方法比較麻煩,也許后面會找到更簡便的辦法。
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
