Python循環語句
for 循環:
可以遍歷任何可迭代對象,如一個列表或者字符串。
用于有明確循環對象或次數。
語法格式:
for 變量名 in 可迭代對象:
# 循環主體 遍歷可迭代對象中的所有元素
實例:
# 循環打印列表中每個元素
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in sites:
print(site)
# 循環打印字典中所有體溫異常人員的工號和體溫
temperature_dict = {"101": 36.5, "102": 36.2, "103": 36.3, "104": 38.6, "105": 36.6}
for temperature_tuple in temperature_dict.items(): # 遍歷字典中所有鍵值對組成的元祖列表
staff_id = temperature_tuple[0]
temperature = temperature_tuple[1]
if temperature >= 38:
print(staff_id, temperature)
# 以下寫法與上面的代碼功能相同,只是簡化了變量的賦值操作
for staff_id, temperature in temperature_dict.items(): # 將元祖中元素的值按順序賦值給 for 循環中的變量
if temperature >= 38:
print(staff_id, temperature)
# 循環打印字符串中每個字符
word = 'runoob'
for letter in word:
print(letter)
# 整數范圍值可以配合 range() 函數使用
# 循環打印 0 到 5 的所有數字:
for number in range(0, 6):
print(number)
# 計算 1 + 2 + 3 ... + 100 的和并打印
total = 0
for i in range(1, 101):
total = total + i
print(total)
關于 range() 函數用法參考:https://www.runoob.com/python3/python3-func-range.html
while 循環:
直到 判斷條件 為假時結束循環,否則一直執行循環。
用于循環次數未知的情況。
語法格式:
while 判斷條件:
# 循環主體,條件成立時執行
實例:
# 計算 1 到 100 的總和
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和為: %d" % (n,sum)) # 輸出結果:1 到 100 之和為: 5050
#用戶輸入任意數字求平均值,當輸入q時終止程序
total = 0
count = 0
user_input = input("請輸入數字(完成所有數字輸入后,請輸入q終止程序):")
while user_input != "q":
num = float(user_input)
total += num
count += 1
user_input = input("請輸入數字(完成所有數字輸入后,請輸入q終止程序):")
if count == 0:
result = 0
else:
result = total / count
print("您輸入的數字平均值為" + str(result))
break 和 continue 語句:
break 語句可以跳出 for 和 while 的循環體,終止循環。
continue 語句可以跳過當前循環塊中的剩余語句,然后繼續進行下一輪循環。
實例:
# break 跳出循環體,終止循環
for letter in 'Runoob':
if letter == 'o':
break
print (letter, end=" ") # 打印內容空格分隔,不換行
print('循環結束')
# 輸出結果:R u n 循環結束
# continue 跳過本次循環的后續語句,開始下次循環
for letter in 'Runoob': # 第一個實例
if letter == 'o': # 字母為 o 時跳過輸出
continue
print (letter, end=" ")
print('循環結束')
# 輸出結果:R u n b 循環結束
# break 跳出循環體,終止循環
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n, end=" ")
print('循環結束')
# 輸出結果:4 3 循環結束
# continue 跳過本次循環的后續語句,開始下次循環
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n, end=" ")
print('循環結束')
# 輸出結果:4 3 1 0 循環結束
相關學習資料:
3小時快速入門Python
Python3教程
浙公網安備 33010602011771號