流程控制之 IF 和 while
阿新 • • 發佈:2020-12-30
一、條件
條件可以是:
1.顯示布林值(比較運算子,也可以是True和false)
2.y隱式布林值(所有的值都可以當成條件,其中0、None、空【空字串、空列表、空字典】代表的布林值為Flase)
邏輯運算子:not 、and、or、
not:把緊跟後面的條件結果取反
and:連線左右兩個條件,所有條件都為True,j結果才為True
or:連線左右兩個條件,只要有一個條件為True,結果就為True;若兩個條件都為Flase,結果才為Flase。
優先順序:not > and > or
成員運算子:in、
print('name' in {'name':'bob','age':'123','male':'man'}) #在字典中 要用Key來判斷,不能用value print('name' in ['name','bob','age','123','male','man'])#在列表中
身份運算子 : is (判斷ID是否相等)
二、流程控制之if判斷
語法一:
if 條件: 程式碼1 程式碼2 程式碼3
語法二:
if 條件: 程式碼1 程式碼2 程式碼3 else:#條件不成立,才執行 程式碼1 程式碼2 程式碼3
語法三:
if 條件2: 程式碼1 程式碼2 程式碼3 elif 條件2:#新增額外的條件(可新增多個,但只要條件成立一個,後面就不再執行) 程式碼1 程式碼2 程式碼3
語法四:
if 條件1: 程式碼1 程式碼2 程式碼3 elif 條件2:#新增額外的條件(可新增多個,但只要條件成立一個,後面就不再執行) 程式碼1 程式碼2 程式碼3 else:#上述條件都不成立,才執行 程式碼1 程式碼2 程式碼3
三、短路運算
偷懶原則,偷懶到哪裡,就把當前值返回
num_1 = 10 > 3 and98 < 23 or 78 == 78 and 90 > 23 print(num_1)
四、深淺copy
淺copy:針對不可變和可變型別沒有進行區分(只COPY了第一層)
list1=['name','age',42] list2=list.copy(list1)#把原列表第一層的記憶體地址不區分的一模一樣拷貝一份 print(list1) =======》['name', 'age', 42] print(list2) =======》['name', 'age', 42]
深copy: (每一層都進行了copy)
針對可變型別進行區分對待,值還是用原來的值。(copy一個列表,並且改操作完全與原列表獨立開)
五、流程控制之While迴圈
語法:
while 條件: 程式碼1 程式碼2 程式碼3
count = 0 while count < 6:#t條件迴圈 ,條件成立一直迴圈 print(count) count += 1 print('棒棒棒')
死迴圈
純計算無IO的死訊會導致致命的效率問題
while 1: #如有必要可這樣寫 while ture:
應用:
name = 'JAKE' sercrt = 'asd' while True:#只要條件為真就一直迴圈 inp_name = input('請輸入你的賬號:') inp_password = input('請輸入你的密碼:') if inp_name == name and inp_password == sercrt: print('登入成功') else: print('請重新登入')
退出迴圈:
方式一:
name = 'JAKE' sercrt = 'asd' exit_1 = True while exit_1: # 只要條件為真就一直迴圈 inp_name = input('請輸入你的賬號:') inp_password = input('請輸入你的密碼:') if inp_name == name and inp_password == sercrt: print('登入成功') exit_1 = False else: print('請重新登入')
方式二:break,只要執行到break就會結束本層迴圈
name = 'JAKE' sercrt = 'asd' while True: inp_name = input('請輸入你的賬號:') inp_password = input('請輸入你的密碼:') if inp_name == name and inp_password == sercrt: print('登入成功') break # 結束本層迴圈 else: print('請重新登入')
#每一層迴圈的結束都需要Break來結束本層的迴圈 while True: while True: while True: break break break
while迴圈巢狀:
name = 'JAKE' sercrt = 'asd' tag = True while tag: inp_name = input('請輸入你的賬號:') inp_password = input('請輸入你的密碼:') if inp_name == name and inp_password == sercrt: print('登入成功') while tag: amd = input('請輸入你要進行的操作:') if amd == 'q': tag = False else: print('命令{x}正在執行,'.format(x=amd)) else: print('請重新登入')
while + continue:#結束本次迴圈,直接進入下一次。(在continue之後新增同級程式碼毫無意義,無法執行到)
count = 0 while count <= 5: if count == 3: count += 1 continue print(count) count += 1
while + else:(else包含的程式碼會在while迴圈結束後,並且沒有被break打斷才會執行)
name = 'JAKE' sercrt = 'asd' count = 0 while count < 3: inp_name = input('請輸入你的賬號:') inp_password = input('請輸入你的密碼:') if inp_name == name and inp_password == sercrt: print('登入成功') while True: amd = input('請輸入你要進行的操作:') if amd == 'q': break else: print('命令{x}正在執行,'.format(x=amd)) break else: print('請重新登入') count += 1 else: print('輸錯賬號密碼三次。')