1. if 語句
- if語句支持嵌套
- 當代碼塊不想執行任何內容時,需用pass占位
if 條件: 代碼塊 else: 代碼塊
if 條件: 代碼塊 elif 條件: 代碼塊 else: 代碼塊
if 1==1: if 2==2: print('Hello') else: print('welcome') else: print('bye')
if 1==1: pass else: print('hello')
2. while循環語句
# 死循環 import time while 1==1: print('OK',time.time()) #-------------------------------------------- import time count = 0 while count < 10: print('OK',time.time()) count += 1 print(123) #-------------------------------------------- count = 0 while count < 10: print(count) count += 1 else: print('else') print('...')
# 使用while循環輸入1 2 3 4 5 6 8 9 10 count = 1 while count < 11: if count != 7: print(count,end=' ') count += 1 else: print(' ',end=' ') count += 1 # ------------------------------------------------- # 求1-100的所有數的和 s = 0 count = 0 while count < 100: count +=1 s += count print(s) # ------------------------------------------------- # 輸出1-100內的所有奇數 count = 1 while count <= 100: if count%2 != 0: print(count, end=' ') count += 1 # ------------------------------------------------- #輸出1-100內的所有偶數 count = 1 while count <= 100: if count%2 ==0: print(count, end=' ') count += 1 # ------------------------------------------------- #求1-2+3-4+5...99的所有數的和 count = 0 s1 = 0 s2 = 0 while count < 99: count += 1 if count%2 !=0: s1 += count else: s2 += count print(s1-s2) # 即就是: count = 1 s = 0 while count < 100: if count%2 !=0: s += count else: s -= count count += 1 print(s) # ------------------------------------------------- #用戶登錄(三次機會重試) count = 0 while count < 3: user = input('請輸入用戶名:') pwd = input('請輸入密碼:') if user == 'root' and pwd == 'root': print('歡迎登錄') break else: if count != 2: print('用戶名或密碼輸入有誤,請重新輸入,若連續輸入錯誤3次,今日將鎖定賬戶') else: print('連續輸入錯誤3次,賬戶已鎖定') count += 1
3. for循環語句
for 變量名 in 字符串 代碼塊
4. break和continue
- continue,終止當前循環,開始下一次循環
- break,終止所有循環
count = 0 while count < 10: #當count等於7時,執行continue終止當前循環,不再執行后面的print和count+=1,直接回到while開頭開始下一次循環 if count == 7: count += 1 continue print(count) count += 1 # ------------------------------------------------- count = 0 while count < 10: count += 1 print(count) break print(111) print('end') #結果為1和end,遇到break終止所有循環,不會執行print(111),直接跳出循環向下繼續執行 # ------------------------------------------------- test = '朝辭白帝彩雲間' for item in test: print(item) break # 朝 for item in test: continue print(item) # 什么也不輸出