day07-while,for循環

一、循環語句

Python提供了for循環和while循環
while在給定的判斷條件爲 true 時執行循環體,不然退出循環體。
for重複執行語句
嵌套循環能夠在while循環體中嵌套for、while循環python

二、while語句

while語句用於循環執行程序,即在某條件下,循環執行某段程序,以處理須要重複處理的相同任務。其基本形式爲:
while判斷條件:
        執行語句……
執行語句能夠是單個語句或語句塊。判斷條件能夠是任何表達式,任何非零、或非空(null)的值均爲true,當判斷條件假false時,循環結束。app

例子:使用while循環輸入 1 2 3 4 5 6 8 9 10less

1 i = 0
2 while i < 10:
3     i+=1
4     if i == 7:
5         continue
6     else:
7         print(i)

 

輸出 1-100 內的全部奇數函數

1 i = 1
2 while i <=100:
3     if i%2 == 1:
4         print(i)
5     i+=1

求1-2+3-4+5 ... 99的全部數的和ui

1 result = 0
2 i = 1
3 while i <=99:
4     if i%2 == 0:
5         result = result - i
6     else:
7         result = result + i
8     i+=1
9 print(result)

 

三、while循環使用else語句

在 python 中,while … else 在循環條件爲false時執行else語句塊:spa

實例code

1 count = 0
2 while count < 5:
3     print (count, " is less than 5")
4     count = count + 1
5 else:
6     print (count, " is not less than 5")

以上實例輸出結果爲:orm

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5blog

四、for語句

for循環能夠遍歷任何序列的項目,如一個列表或者一個字符串,不能遍歷int數值。遞歸

for循環的語法格式以下:

1 msg = 'abcd'
2 for i in msg:
3     print (i)

a
b
c
d

計算1-100的和:

1 sum = 0
2 for x in range(101):
3     sum = sum + x
4 print(sum)

輸出a-z

1 for j in range(ord('a'), ord('z')+1):
2     print(chr(j),end=' ')

a b c d e f g h i j k l m n o p q r s t u v w x y z

1 a = []
2 for i in range(ord('a'),ord('z')):
3     a.append(chr(i))
4 print(a)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']

ord函數將字符轉換爲整數顯示,chr函數將整數轉換爲字符顯示

while和for循環的區別:
while循環通常經過數值是否知足來肯定循環的條件
for循環通常是對能保存多個數據的變量,進行遍歷

五、經過序列索引迭代

另一種執行循環的遍歷方式是經過索引,以下實例:

1 fruits = ['banana', 'apple', 'mango']
2 for index in range(len(fruits)):
3     print('第%s個水果是:%s'%(index+1,fruits[index]))

第1個水果是:banana
第2個水果是:apple
第3個水果是:mango

六、循環使用else語句

在 python 中,for … else表示這樣的意思,for中的語句和普通的沒有區別,else中的語句會在循環正常執行完(即 for不是經過break跳出而中斷的)的狀況下執行,while … else 也是同樣。

1 for num in range(10,20):
2     for i in range(2,num):
3         if num%i == 0:
4             j = num//i
5             print('%s等於%s * %s'%(num,i,j))
6             break
7     else:
8         print('%s是一個質數'%num)

10等於2 * 5
11是一個質數
12等於2 * 6
13是一個質數
14等於2 * 7
15等於3 * 5
16等於2 * 8
17是一個質數
18等於2 * 9
19是一個質數

七、循環嵌套

7.一、for循環嵌套語法實現九九乘法表:

1 for x in range(1,10):
2     for y in range(1,x+1):
3         print('%s*%s=%-4s'%(y,x,x*y),end='')
4     print()

%2s表示這個字符最少佔用2個字符,若是隻有一個字符則靠右顯示
%-2s表示這個字符最少佔用2個字符,若是隻有一個字符且字符靠左顯示
默認狀況下,print() 除了打印你提供的字符串以外,還會打印一個換行符,因此每調用一次 print() 就會換一次行,如同上面同樣。

7.二、while循環嵌套語法實現九九乘法表:

1 i = 1
2 while i < 10:
3     j = 1
4     while j <= i:
5         print('{}*{}={:<4d}'.format(j,i,j*i),end='')
6         j+=1
7     i+=1
8     print()

7.三、列表解析實現九九乘法表:

print ('\n'.join([' '.join(['%s*%s=%-4s'%(y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))

print後面輸出的內容默認是自帶回車的,在Python2中,print最後面加上一個逗號表示不換行,在Python3中,print最後面加上一個,end=''或者,end=""表示不換行。

1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

八、循環控制語句

break語句

用來終止循環語句,即循環條件沒有False條件或者序列還沒被徹底遞歸完,也會中止執行循環語句。
break語句可用在while和for循環中。
若是使用嵌套循環,break語句將中止執行最深層的循環,並開始執行下一行代碼。

continue語句
用來告訴Python跳過當前循環的剩餘語句,而後繼續進行下一輪循環。
continue語句可用在while和for循環中。
continue語句跳出本次循環,而break跳出整個循環。

九、例子:斐波那契(Fibonacci)數列

打印斐波那契數列。這個數列前兩項爲 1,以後的每個項都是前兩項之和。因此這個數列看起來就像這樣:1,1,2,3,5,8,13 ......

1 a,b = 0,1
2 while b < 100:
3     print(b,end=' ')
4     a,b = b,a+b

運行程序:
1 1 2 3 5 8 13 21 34 55 89

第一行代碼中咱們初始化a和b。當b的值小於100的時候,循環執行代碼。

循環裏咱們首先打印b的值,而後在下一行將a+b的值賦值給b,b的值賦值給a。
你能夠這樣理解,Python中賦值語句執行時會先對賦值運算符右邊的表達式求值,而後將這個值賦值給左邊的變量。

十、while循環中利用標誌位退出循環

一、使用break退出循環(若是有多層循環時,須要考慮break的位置,不方便)

flag = True
count = 0
while flag:
    user = input('user>>: ')
    password = input('password>>: ')
    count += 1
    if count ==3:
        print('too many')
        break
    if user == 'admin' and password == '123':
        print('success')
        while True:
            cmd = input('cmd>>: ')
            if cmd == 'q':
                break
        break

二、利用標誌位退出(將flag定義爲True,循環中可使用flag做爲條件,當須要退出全部循環時,能夠改變flag的值爲False便可,更方便)

flag = True
count = 0
while flag:
    user = input('user>>: ')
    password = input('password>>: ')
    count += 1
    if count ==3:
        print('too many')
        flag=False
    if user == 'admin' and password == '123':
        print('success')
        while flag:
            cmd = input('cmd>>: ')
            if cmd == 'q':
                flag=False
相關文章
相關標籤/搜索