咱們都知道,程序執行的語句只有三種,分別是順序語句(從上到下)、條件語句、循環語句,程序默認都是從上往下進行執行,那麼python的條件語句和循環語句又是什麼樣的呢?且聽我慢慢跟你講解python
首先咱們來看 pythond的條件語句:---------->if條件語句windows
語法:只有if,沒有elsespa
例如:code
if 1==1 :blog
print(''abc'')內存
print(''abcdef'')input
print(''abcdef'')class
(單分支)循環
語法: if 條件:語法
代碼塊
else:
代碼塊
(多分支)
語法: if 條件:
代碼塊
elif 條件:
代碼塊
-------
else:
代碼塊
注意:代碼塊的縮進要一致,通常縮進4格,不然報錯
語法:if語句嵌套
例如:
1 if 1==1: 2 if 2==2: 3 print('我是pythonman') 4 print('我是pythonman_1') 5 else: 6 print('內存判斷分支打印') 7 else: 8 print('abc')
程序執行結果是:
我是pythonman
我是pythonman_1
如今 咱們把代碼改一下:
if 1==1: if 2!=2: print('我是pythonman') print('我是pythonman_1') else: print('內存判斷分支打印') else: print('abc')
程序執行結果是:
內存判斷分支打印
如今咱們來看python循環語句:------->while循環語句
語法1:基本語法
while 條件:
代碼塊
例如:打印1-10的數字
1 count=1 2 while count<11: 3 print(count) 4 count=count+1
語法2: while else
例如:
count=1 while count<11: print(count) count=count+1 else: print("while條件的其餘狀況打印")
執行結果:
1
2
3
4
5
6
7
8
9
10
while條件的其餘狀況打印
說明:else執行是在 while 條件 當 count<11不知足時,纔會執行 else代碼塊內容,因此咱們看到了如上打印的結果
語法3:continue、break的使用
continue 終止當前循環,開始下一次循環:它下面的代碼不執行,從新回到循環的初始位置從新開始
break 終止所有循環:循環終止,不在執行
例如:
count=1 while count<11: if count==7: count=count+1 continue print(count) count=count+1
代碼說明:當程序執行到count7的時候,增長1,就回到了循環的起點,而不會執行continue下面的print語義,也就是7不會打印,因此程序執行
結果就是 打印1-10的數字不包括7
例如:
count=1 while count<11: if count==7: break print(count) count=count+1
代碼說明:程序在執行到count=7的時候,break,整個循環終止了,因此程序執行結果是 打印了1-6
爲了讓你們更好的熟悉語法,如今咱們來練習幾道題目吧!
請看題:1 使用while循環輸入1 2 3 4 5 6 8 9 10
2 輸出1-100內全部奇數
3 輸出1-100內全部的偶數
4 求1-100的全部數的和
5 求1-2+3-4+5-----99的全部數的和
代碼參考:
1
count=1 while count<11: if count==7: pass else: print(count) count=count+1
2
count=1 while count<101: temp=count%2 if temp!=0: print(count) else: pass count=count+1
3
count=1 while count<101: temp=count%2 if temp==0: print(count) else: pass count=count+1
4
count=1 s=0 while count<101: s=s+count count=count+1 print(s)
5
count=0 s=0 while count<101: temp=count%2 if temp==0: count = count + 1 s = s -count else: count = count + 1 s = s + count print(s)
綜合練習:用戶登錄三次機會
1 count=0 2 while count<3: 3 a=input("請輸入用戶名:") 4 b=input("請輸入密碼:") 5 if a=="root" and b=="123": 6 print("歡迎進入windows系統") 7 break 8 else: 9 print("用戶名或密碼輸入錯誤,請從新輸入") 10 count = count + 1 11 print("程序運行結束")