pythotn條件分支與循環(huán)詳解
if條件分支
1. if語句基本用法
if boolean_value: 子代碼模塊1
1)判斷條件
boolean_value是if語句判斷條件,以布爾值的形式判斷if語句是否執(zhí)行子代碼模塊1。當(dāng)boolean_value值為True時,則執(zhí)行在代碼模塊1;當(dāng)值為False時,就不會執(zhí)行。
2)示例
>>> if True: print("hello world") hello world
if語句支持多行執(zhí)行,但是必須要加冒號。
對于boolean_value,除了可以使用布爾值外,還可以使用表達式,表達式計算最終結(jié)果為布爾值。
hello world >>> if 5>2: print("xxxxx") xxxxx >>> if 2>5: print("ok") >>>
2. 雙分支判斷
if boolean_value: 子代碼模塊1 else: 子代碼模塊2
示例
>>> if False: print("ok") else: print("no") no
3. 多條件多分支判斷
if boolean_value1: 子代碼模塊1 elif boolean_value2: 子代碼模塊2 else: 子代碼模塊3
這里引入的elif進行新的條件判斷,在if語句中elif可以依據(jù)實際情況連續(xù)使用,但是else只能用在最后而且只能使用一次。
4. 案例
案例來源《python編程從零基礎(chǔ)到項目實戰(zhàn)》劉瑜(著)
要求
(1)用字符串記錄上述內(nèi)容
(2)檢查字符串的長度
(3)用條件判斷找出三酷貓想要找的烏龜,想知道釣了幾只,并告訴是奇數(shù)還是偶數(shù)
#三酷貓釣魚記錄查找 fish_record = "鯽魚5條、鯉魚8條、鰱魚7條、草魚2條、黑魚6條、烏龜1只" print(len(fish_record)) if fish_record[0:2]=="烏龜": print("是烏龜嗎?,是"+fish_record[0:2]) elif fish_record[5:7]=="烏龜": print("是烏龜嗎?,是"+fish_record[5:7]) elif fish_record[10:12]=="烏龜": print("是烏龜嗎?,是"+fish_record[10:12]) elif fish_record[15:17]=="烏龜": print("是烏龜嗎?,是"+fish_record[15:17]) elif fish_record[20:22]=="烏龜": print("是烏龜嗎?,是"+fish_record[20:22]) elif fish_record[25:27]!="烏龜": if int(fish_record[27])%2 == 0: print("找到烏龜了,是%d只,偶數(shù)"%(int(fish_record[27]))) else: print("找到烏龜了,是%d只,奇數(shù)"%(int(fish_record[27])))
while 循環(huán)
1. while語句基本用法
while語句的基本語法格式:
while boolean_value:子代碼模塊1
1)while語法格式說明
boolean_value為while語句的循環(huán)判斷條件。當(dāng)其為True時,會執(zhí)行在代碼模塊1;當(dāng)其值為False時,終止循環(huán)。
boolean_value可以為布爾值,也可以是運算表達式。
示例1:
pwd = '' # 注:這個''代表空字符串 while pwd != '520666': pwd = input('請輸入銀行卡密碼:') print('卡內(nèi)還有999999999999元~')
示例2(嵌套):
while i<2: while i<j: print("%d,"%((i+1)*j)) i -= 1 i += 1
2. 練習(xí)
獲取用戶輸入的任意數(shù),判斷其是否是質(zhì)數(shù)?
# 獲取用戶輸入的任意數(shù),判斷其是否是質(zhì)數(shù)? while True: n = int(input('請輸入數(shù)字:')) if n == 0: print('%d不是質(zhì)數(shù),請重新輸入!'%n) elif n % 2 == 1: print('%d是質(zhì)數(shù)。'%n) break else: continue
總結(jié)
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。