在Python編程語言中,循環是一個非常重要的概念,可以幫助我們在代碼中重復執行某些操作。Python支持兩種主要的循環結構:for
循環和 while
循環。
1. for
循環
for
循環用于遍歷一個序列(如列表、元組、字符串)或其他可迭代對象(如字典、集合)。它的基本語法如下:
for variable in iterable:# 執行代碼塊
其中,variable
是一個變量,它將在每次迭代中被賦予 iterable
中的下一個值,iterable
是一個可迭代對象。以下是一些示例:
示例 1:遍歷列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:print(fruit)
輸出:
apple
banana
cherry
示例 2:遍歷字符串
for char in 'hello':print(char)
輸出:
h
e
l
l
o
示例 3:使用 range()
函數
range()
函數用于生成一個數值序列。它通常與 for
循環一起使用。基本語法如下:
for i in range(start, stop, step):# 執行代碼塊
start
:序列的起始值,默認為0。stop
:序列的結束值(不包含在序列中)。step
:步長,默認為1。
示例:
for i in range(5):print(i)
輸出:
0
1
2
3
4
示例 4:遍歷字典
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
for key, value in student.items():print(f'{key}: {value}')
輸出:
name: John
age: 25
courses: ['Math', 'CompSci']
示例 5:嵌套 for
循環
matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]
]for row in matrix:for item in row:print(item, end=' ')print()
輸出:
1 2 3
4 5 6
7 8 9
2. while
循環
while
循環在給定的條件為真時,重復執行目標語句。它的基本語法如下:
while condition:# 執行代碼塊
其中,condition
是一個表達式,當其為真時,執行代碼塊。下面是一些示例:
示例 1:簡單 while
循環
i = 0
while i < 5:print(i)i += 1
輸出:
0
1
2
3
4
示例 2:用戶輸入
user_input = ''
while user_input.lower() != 'exit':user_input = input('Enter something (type "exit" to quit): ')print(f'You entered: {user_input}')
示例 3:無限循環和 break
while True:user_input = input('Enter something (type "exit" to quit): ')if user_input.lower() == 'exit':breakprint(f'You entered: {user_input}')
示例 4:continue
語句
i = 0
while i < 10:i += 1if i % 2 == 0:continueprint(i)
輸出:
1
3
5
7
9
3. for
循環和 while
循環的區別
- 使用場景:
for
循環通常用于遍歷固定長度的序列,而while
循環適用于未知長度的循環或需要在滿足特定條件時終止的循環。 - 可讀性:
for
循環通常更簡潔,更易讀,尤其是在處理序列時。while
循環在處理復雜條件時更靈活。 - 性能:在許多情況下,
for
循環的性能可能稍好,因為它們在許多情況下可以更有效地進行優化。
4. 循環中的常見問題
無限循環
無限循環是指循環條件永遠為真的循環。通常是由于條件未正確更新導致的。示例:
i = 0
while i < 5:print(i)# 缺少 i += 1,導致 i 永遠為 0
break
和 continue
break
:立即終止循環。continue
:跳過當前迭代,繼續下一次迭代。
示例:
for i in range(10):if i == 5:breakprint(i)for i in range(10):if i % 2 == 0:continueprint(i)
嵌套循環中的 break
在嵌套循環中使用 break
只會終止內層循環。示例:
for i in range(3):for j in range(3):if j == 1:breakprint(f'i={i}, j={j}')
輸出:
i=0, j=0
i=1, j=0
i=2, j=0
循環與條件語句結合
for i in range(1, 11):if i % 2 == 0:print(f'{i} 是偶數')else:print(f'{i} 是奇數')
輸出:
1 是奇數
2 是偶數
3 是奇數
4 是偶數
5 是奇數
6 是偶數
7 是奇數
8 是偶數
9 是奇數
10 是偶數
5. 實踐案例
案例 1:計算列表中所有元素的和
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:total += num
print(f'列表元素的和為: {total}')
案例 2:找出列表中的最大值
numbers = [3, 41, 12, 9, 74, 15]
max_num = numbers[0]
for num in numbers:if num > max_num:max_num = num
print(f'列表中的最大值是: {max_num}')
案例 3:使用 while
循環實現猜數字游戲
import randomsecret_number = random.randint(1, 100)
guess = None
attempts = 0while guess != secret_number:guess = int(input('猜一個 1 到 100 之間的數字: '))attempts += 1if guess < secret_number:print('猜低了')elif guess > secret_number:print('猜高了')else:print(f'恭喜你,猜對了!你一共猜了 {attempts} 次。')
案例 4:生成乘法表
for i in range(1, 10):for j in range(1, 10):print(f'{i} x {j} = {i * j}', end='\t')print()
輸出:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5 1 x 6 = 6 1 x 7 = 7 1 x 8 = 8 1 x 9 = 9
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27
4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20 4 x 6 = 24 4 x 7 = 28 4 x 8 = 32 4 x 9 = 36
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45
6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36 6 x 7 = 42 6 x 8 = 48 6 x 9 = 54
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63
8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64 8 x 9 = 72
9 x 1 = 9 9 x 2 = 18 9 x 3 = 27 9 x 4 = 36 9 x 5 = 45 9 x 6 = 54 9 x 7 = 63 9 x 8 = 72 9 x 9 = 81
案例 5:統計字符串中每個字符的出現頻率
text = 'hello world'
char_count = {}for char in text:if char in char_count:char_count[char] += 1else:char_count[char] = 1for char, count in char_count.items():print(f'{char}: {count}')
輸出:
h: 1
e: 1
l: 3
o: 2: 1
w: 1
r: 1
d: 1
循環結構是Python編程中的基本概念,for
循環和 while
循環各有其適用場景和優勢。for
循環適用于遍歷已知長度的序列,而 while
循環則在處理需要滿足特定條件時特別有用。理解并掌握這兩種循環的用法,可以大大提高代碼的可讀性和效率。