目錄
- if條件分支
- 1. if語(yǔ)句基本用法
- 2. 雙分支判斷
- 3. 多條件多分支判斷
- 4. 案例
- while 循環(huán)
- 1. while語(yǔ)句基本用法
- 2. 練習(xí)
- 總結(jié)
if條件分支
1. if語(yǔ)句基本用法
1)判斷條件
boolean_value是if語(yǔ)句判斷條件,以布爾值的形式判斷if語(yǔ)句是否執(zhí)行子代碼模塊1。當(dāng)boolean_value值為T(mén)rue時(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ù)
#三酷貓釣魚(yú)記錄查找
fish_record = "鯽魚(yú)5條、鯉魚(yú)8條、鰱魚(yú)7條、草魚(yú)2條、黑魚(yú)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)其為T(mén)rue時(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 i2:
while ij:
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)容!
您可能感興趣的文章:- Python3.4學(xué)習(xí)筆記之常用操作符,條件分支和循環(huán)用法示例
- Python for 循環(huán)語(yǔ)句的使用
- Python基礎(chǔ)之循環(huán)語(yǔ)句相關(guān)知識(shí)總結(jié)
- Python循環(huán)結(jié)構(gòu)詳解
- python基礎(chǔ)詳解之if循環(huán)語(yǔ)句