1. 程式人生 > 其它 >【python基礎教程】(3)Python3 迴圈語句

【python基礎教程】(3)Python3 迴圈語句

Python3 迴圈語句

Python 中的迴圈語句有 for 和 while。

Python 迴圈語句的控制結構圖如下所示:

1、while 迴圈

Python 中 while 語句的一般形式:

while 判斷條件(condition):
    執行語句(statements)……

執行流程圖如下:

同樣需要注意冒號和縮排。另外,在 Python 中沒有 do..while 迴圈。

以下例項使用了 while 來計算 1 到 100 的總和:

n = 100
sum = 0
count = 1

while count <= n:
    sum = sum + count
    count 
= count + 1 print("1加到100的和為%d" % sum)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01.py
1加到100的和為5050

Process finished with exit code 0

2、無限迴圈

我們可以通過設定條件表示式永遠不為 false 來實現無限迴圈,例項如下:

# -*- coding:utf-8 -*-

while True:
    num = int(input("請輸入一個數字:"))
    
print("您輸入的數字是%d" % num)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
請輸入一個數字:1
您輸入的數字是1
請輸入一個數字:3
您輸入的數字是3
請輸入一個數字:4
您輸入的數字是4
請輸入一個數字:

你可以使用CTRL+C來退出當前的無限迴圈。

無限迴圈在伺服器上客戶端的實時請求非常有用。

3、while 迴圈使用 else 語句

如果 while 後面的條件語句為 false 時,則執行 else 的語句塊。

語法格式如下:

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

expr 條件語句為 true 則執行 statement(s) 語句塊,如果為 false,則執行 additional_statement(s)。

迴圈輸出數字,並判斷大小:

# -*- coding:utf-8 -*-

count = 0
while count <5:
    print("count小於5:", count)
    count = count + 1
else:
    print("count大於5了:", count)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
count小於5: 0
count小於5: 1
count小於5: 2
count小於5: 3
count小於5: 4
count大於5了 5

Process finished with exit code 0

4、簡單語句組

類似if語句的語法,如果你的while迴圈體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:

# -*- coding:utf-8 -*-

flag = 1
while (flag): print("hello.yin")

print("hello.yin! good bye~")

執行結果:

hello.yin
hello.yin
hello.yin
hello.yin
hello.yin
hello.yin
.......

5、for語句

Python for 迴圈可以遍歷任何可迭代物件,如一個列表或者一個字串。

for迴圈的一般格式如下:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

流程圖:

Python for 迴圈例項:

# -*- coding:utf-8 -*-

lang = ['python', 'java', 'html', 'php']
for x in lang:
    print(x, end=',')

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
python,java,html,php,
Process finished with exit code 0

以下 for 例項中使用了 break 語句,break 語句用於跳出當前迴圈體:

# -*- coding:utf-8 -*-

lang = ["python", "java", "html", "php"]

for x in lang:
    if x == "html":
        print("找到html~")
        break
    print("繼續迴圈:", x)

else:
    print("沒有找到html~")

print("完成迴圈~")

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
繼續迴圈: python
繼續迴圈: java
找到html~
完成迴圈~

Process finished with exit code 0

6、range()函式

如果你需要遍歷數字序列,可以使用內建range()函式。它會生成數列,例如:

例項:

# -*- coding:utf-8 -*-

for i in range(10):
    print(i)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
0
1
2
3
4
5
6
7
8
9

Process finished with exit code 0

你也可以使用range指定區間的值:

# -*- coding:utf-8 -*-

for i in range(5, 10):
    print(i)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
5
6
7
8
9

Process finished with exit code 0

也可以使range以指定數字開始並指定不同的增量(甚至可以是負數,有時這也叫做'步長'):

# -*- coding:utf-8 -*-

for i in range(2, 10, 3):
    print(i)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
2
5
8

Process finished with exit code 0

您可以結合range()和len()函式以遍歷一個序列的索引,如下所示氣泡排序:

# -*- coding:utf-8 -*-


def bubble_sort(arr):
    n = len(arr)

    for i in range(n):
        for j in range (0,n-i-1):
            if arr[j] >arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]


arr = [323, 43, 13, 76, 2, 989]
bubble_sort(arr)
for i in range(len(arr)):
    print("%d" % arr[i])

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
2
13
43
76
323
989

Process finished with exit code 0

您可以結合range()和len()函式以遍歷一個序列的索引,如下所示:

# -*- coding:utf-8 -*-

web = ["google", "baidu", "bing", "yahoo", "sina", "souhu"]

for i in range(len(web)):
    print("%d:" %i, web[i] )

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
0: google
1: baidu
2: bing
3: yahoo
4: sina
5: souhu

Process finished with exit code 0

7、break 和 continue 語句及迴圈中的 else 子句

break 執行流程圖:

continue 執行流程圖:

while 語句程式碼執行過程:

for 語句程式碼執行過程:

break語句可以跳出 for 和 while 的迴圈體。如果你從 for 或 while 迴圈中終止,任何對應的迴圈 else 塊將不執行。

continue語句被用來告訴 Python 跳過當前迴圈塊中的剩餘語句,然後繼續進行下一輪迴圈。

例項

while 中使用 break:

# -*- coding:utf-8 -*-

n = 5
while n > 0:
    n = n-1
    if n == 2:
        break
    print(n)
    
print("迴圈完成!")

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
4
3
迴圈完成!

Process finished with exit code 0

while 中使用 continue:

# -*- coding:utf-8 -*-

n = 5
while n > 0:
    n = n-1
    if n == 2:
        continue
    print(n)

print("迴圈完成!")

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
4
3
1
0
迴圈完成!

Process finished with exit code 0

更多例項如下:

# -*- coding:utf-8 -*-

for letter in "helloyin":
    if letter == "n":
        break
    print("當前字母為%s" % letter)


var = 10

while var > 0:
    var = var-1
    if var < 5:
        break
    print("正在迴圈%d" % var)
print("goof bye hello yin")

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
當前字母為h
當前字母為e
當前字母為l
當前字母為l
當前字母為o
當前字母為y
當前字母為i
正在迴圈9
正在迴圈8
正在迴圈7
正在迴圈6
正在迴圈5
goof bye hello yin

Process finished with exit code 0

continue更多例項:

# -*- coding:utf-8 -*-

for letter in "helloyin":
    if letter == "o":
        continue
    print("當前字母為%s" % letter)


var = 10

while var > 0:
    var = var-1
    if var == 5:
        continue
    print("正在迴圈%d" % var)
print("goof bye hello yin")

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
當前字母為h
當前字母為e
當前字母為l
當前字母為l
當前字母為y
當前字母為i
當前字母為n
正在迴圈9
正在迴圈8
正在迴圈7
正在迴圈6
正在迴圈4
正在迴圈3
正在迴圈2
正在迴圈1
正在迴圈0
goof bye hello yin

Process finished with exit code 0

迴圈語句可以有 else 子句,它在窮盡列表(以for迴圈)或條件變為 false (以while迴圈)導致迴圈終止時被執行,但迴圈被 break 終止時不執行。

如下例項用於查詢質數的迴圈例子:

for n in range(2, 10):
    for x in range(2, n):  # 不包括本身
        if n % x == 0:
            print(n, "等於", x, "*", n//x)
            break

    else:
        print("%d是質數" % n)

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
2是質數
3是質數
4 等於 2 * 2
5是質數
6 等於 2 * 3
7是質數
8 等於 2 * 4
9 等於 3 * 3

Process finished with exit code 0

8、pass 語句

Python pass是空語句,是為了保持程式結構的完整性。

pass 不做任何事情,一般用做佔位語句,如下例項

例項:

>>>while True:
...     pass  # 等待鍵盤中斷 (Ctrl+C)

例項,最小的類:

>>>class MyEmptyClass:
...     pass

例項:

for letter in "helloyin":
    if letter == "o":
        pass
        print("執行pass")
    print("當前字母是%s" % letter)

print("helloyin~good bye~")

執行結果:

C:\Users\yzp\PycharmProjects\base_practice\Scripts\python.exe D:/00test/base_practice/01test.py
當前字母是h
當前字母是e
當前字母是l
當前字母是l
執行pass
當前字母是o
當前字母是y
當前字母是i
當前字母是n
helloyin~good bye~

Process finished with exit code 0

迴圈語句可以有 else 子句,它在窮盡列表(以for迴圈)或條件變為 false (以while迴圈)導致迴圈終止時被執行,但迴圈被 break 終止時不執行。

如下例項用於查詢質數的迴圈例子:

本部落格所有文章僅用於學習、研究和交流目的,歡迎非商業性質轉載。

本文來自部落格園,作者:hello_殷,轉載請註明原文連結:https://www.cnblogs.com/yinzuopu/p/15552944.html

本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,並保留此段宣告,否則保留追究法律責任的權利。