pythotn條件分支與循環(huán)詳解
if條件分支
1. if語(yǔ)句基本用法
if boolean_value: 子代碼模塊1
1)判斷條件
boolean_value是if語(yǔ)句判斷條件,以布爾值的形式判斷if語(yǔ)句是否執(zhí)行子代碼模塊1。當(dāng)boolean_value值為True時(shí),則執(zhí)行在代碼模塊1;當(dāng)值為False時(shí),就不會(huì)執(zhí)行。
2)示例
>>> if True:
print("hello world")
hello world
if語(yǔ)句支持多行執(zhí)行,但是必須要加冒號(hào)。
對(duì)于boolean_value,除了可以使用布爾值外,還可以使用表達(dá)式,表達(dá)式計(jì)算最終結(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進(jìn)行新的條件判斷,在if語(yǔ)句中elif可以依據(jù)實(shí)際情況連續(xù)使用,但是else只能用在最后而且只能使用一次。
4. 案例
案例來(lái)源《python編程從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)》劉瑜(著)
要求
(1)用字符串記錄上述內(nèi)容
(2)檢查字符串的長(zhǎng)度
(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語(yǔ)句基本用法
while語(yǔ)句的基本語(yǔ)法格式:
while boolean_value:子代碼模塊1

1)while語(yǔ)法格式說(shuō)明
boolean_value為while語(yǔ)句的循環(huán)判斷條件。當(dāng)其為True時(shí),會(huì)執(zhí)行在代碼模塊1;當(dāng)其值為False時(shí),終止循環(huán)。
boolean_value可以為布爾值,也可以是運(yùn)算表達(dá)式。


示例1:
pwd = '' # 注:這個(gè)''代表空字符串
while pwd != '520666':
pwd = input('請(qǐng)輸入銀行卡密碼:')
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('請(qǐng)輸入數(shù)字:'))
if n == 0:
print('%d不是質(zhì)數(shù),請(qǐng)重新輸入!'%n)
elif n % 2 == 1:
print('%d是質(zhì)數(shù)。'%n)
break
else:
continue
總結(jié)
本篇文章就到這里了,希望能給你帶來(lái)幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信