流程控制即控制流程,具體指控制程序的執行流程,而程序的執行流程分爲三種結構:順序結構(以前咱們寫的代碼都是順序結構)、分支結構(用到if判斷)、循環結構(用到while與for)python
分支結構就是根據條件判斷的真假去執行不一樣分支對應的子代碼git
人類某些時候須要根據條件來決定作什麼事情,好比:若是今天下雨,就帶傘ide
因此程序中必須有相應的機制來控制計算機具有人的這種判斷能力ip
用if關鍵字來實現分支結構,完整語法以下字符串
if 條件1: # 若是條件1的結果爲True,就依次執行:代碼一、代碼2,...... 代碼1 代碼2 ......elif 條件2: # 若是條件2的結果爲True,就依次執行:代碼三、代碼4,...... 代碼3 代碼4 ......elif 條件3: # 若是條件3的結果爲True,就依次執行:代碼五、代碼6,...... 代碼5 代碼6 ......else: # 其它狀況,就依次執行:代碼七、代碼8,...... 代碼7 代碼8 ......# 注意:# 一、python用相同縮進(4個空格表示一個縮進)來標識一組代碼塊,同一組代碼會自上而下依次運行# 二、條件能夠是任意表達式,但執行結果必須爲布爾類型 # 在if判斷中全部的數據類型也都會自動轉換成布爾類型 # 2.一、None,0,空(空字符串,空列表,空字典等)三種狀況下轉換成的布爾值爲False # 2.二、其他均爲True
?僞代碼展現if 條件1: 代碼1 代碼2 代碼3
若是:女人的年齡>30歲,那麼:叫阿姨input
age_of_girl=31if age_of_girl > 30: print('阿姨好')?相親 song='man'age=27is_verygood=Trueis_yes=Falseif song == 'man' and (age > 18 and age < 26 or is_verygood): print('結婚')
?僞代碼展現if 條件1: 代碼1 代碼2 代碼3else: 代碼1 代碼2 代碼3
若是:女人的年齡>30歲,那麼:叫阿姨,不然:叫小姐it
age_of_girl=18if age_of_girl > 30: print('阿姨好')else: print('小姐好')# 結婚song='man'age=27is_verygood=Trueif song == 'man' and (age > 18 and age < 26 or is_verygood): print('結婚')else: print('bujiehun')
?僞代碼展現if 條件1: 代碼1 代碼2 代碼3elif 條件2: 代碼1 代碼2 代碼3elif 條件3: 代碼1 代碼2 代碼3
若是:成績>=90,那麼:優秀class
若是成績>=80且<90,那麼:良好基礎
若是成績>=70且<80,那麼:普通循環
其餘狀況:不好
?成績 score=input('你的分數:')score=int(score)if score >= 90: print('你牛逼')elif score >= 80: print('還不錯')elif score >= 75: print('通常般')else: print('真差勁')
?猜年齡 瓦文的年齡=38count = 1while count <= 5: cnl = input('輸入你猜想的瓦文的年齡:').strip() if cnl.isdigit(): cnl = int(cnl) if cnl > 瓦文的年齡: print('她有這麼老嗎?') print('再猜!睜大眼睛') print('剩餘猜想次數:',count) count+= 1 continue elif cnl < 瓦文的年齡: print('你是眼瞎嗎?她有這麼年輕???') print('再猜錯你日子就到頭了!!!') print('剩餘猜想次數:', count) count+= 1 continue else: print('有眼光啊!小夥子') break else: print('報警紮起來')#在表白的基礎上繼續:#若是表白成功,那麼:在一塊兒#不然:打印。。。age_of_girl=18height=171weight=99is_pretty=Truesuccess=Falseif age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True: if success: print('表白成功,在一塊兒') else: print('什麼愛情不愛情的,愛nmlgb的愛情,愛nmlg啊...')else: print('阿姨好')
練習1: 登錄功能
name=input('請輸入用戶名字:').strip()password=input('請輸入密碼:').strip()if name == 'tony' and password == '123': print('tony login success')else: print('用戶名或密碼錯誤')
練習2:
#!/usr/bin/env python#根據用戶輸入內容打印其權限''' egon --> 超級管理員 tom --> 普通管理員 jack,rain --> 業務主管 其餘 --> 普通用戶 '''name=input('請輸入用戶名字:')if name == 'egon': print('超級管理員')elif name == 'tom': print('普通管理員')elif name == 'jack' or name == 'rain': print('業務主管')else: print('普通用戶')