python自學筆記10:while循環和for循環

條件控制和循環控制是兩種典型的流程控制方法,前面我們寫了 if 條件控制,這節講 for 循環和 while 循環。

循環是另一種控制流程的方式,一個循環體中的代碼在程序中只需要編寫一次,但可能會連續運行多次。在 python 中主要包含兩種循環結構:

  • while 循環,表示滿足某種條件是,重複運行一段固定代碼。
  • for 循環,表示遍歷某組數據,每次取出一個,重複運行一段固定代碼。

while 循環

while 循環的語法和 if 條件非常類似:

while expression:
	statement1

當 expression 條件滿足時,執行 statement1 語句, 語句執行完後,會返回第一行繼續判斷條件是否滿足。如果該條件一直保持滿足狀態,循環語句無法退出,就會出現死循環的狀態。

while True:
	print("hello, you")

爲了讓程序運行到一定階段退出循環體,需要改變條件,當條件改變到不滿足的狀態時,就可以退出循環結構了:

times = 0
while times < 1000:
	print(f"hello you {times}")
	times += 1

for 循環

for 循環是一種更加常用的循環結構,主要作用遍歷一組數據達到循環執行的效果。這組數據通常是字符串,列表,元素,字典等可迭代的數據。

my_string = 'hello you'
for letter in my_string:
    print(letter)

letter 是一個臨時變量,表示每一輪循環從 my_string 中取出來的元素,第一輪循環是 h, 第二輪循環是 e 。臨時變量在退出循環結構之後會失效。

for letter in my_string:
    print(letter)  # YES
print(letter)  # NO

遍歷列表

dalaos = ['小芳''溫暖如初''小蚊子']
for dalao in dalaos:
    print(dalao)

遍歷字符串、列表、元組等數據時,可以使用 enumerate 函數同時獲取索引和值,經常可以用到。

dalaos = ['小芳', '溫暖如初', '小蚊子']
for index, item in enumerate(dalaos):
	print(item)

遍歷字典

遍歷字典默認是獲取 key

user = {"name": "小芳", "age": "17"}
for item in user:
	print(item)

同時獲取 key 和 value 是更常用的做法:

for key, item in user.items():
	print(key, item)

range

range 的作用是生成一個類似於列表的數據,range(6) 生成類似於 [0,1,2,3,4,5] 的數據。當你需要對某段代碼循環運行指定次數,但是又沒有現成的數據可以遍歷時,可以用 range

for item in range(10000):
	print(item)

range() 的參數類似於切片的寫法,當只有一個參數時,表示結束索引號,當有兩個參數時,表示開始和結束的索引號,當有3個參數時,增加步長。

# start, end
for item in range(3,8):
    print(item)

# start, end, step
for item in range(3,8,2):
    print(item)

循環的嵌套

之前我們瞭解到, for 循環作用是對一組數據中的不同元素執行相同的操作(代碼),如果想對不同的元素進行差異化操作,可以使用 for 循環嵌套 if 的組合。

dalaos = ['小芳', '溫暖如初', '小蚊子']
for dalao in dalaos:
	if dalao == '小芳':
	print("村裏有個姑娘,叫小芳。")
else:
	print("沒有你要找的人")

對元素分組:

users = [
    {"name"'yyz'"age"18},
    {"name"'小芳'"age":16},
    {"name"'v'"age"19},
    {"name"'w'"age"20},
]

adult = []
kids = []

for user in users:
    # user =  {"name": 'yyz', "age": 18}
    if user['age'] >= 18:
        adult.append(user)
    else:
        kids.append(user)

        print(adult)
        print(kids)

break

在 while 和 for 的循環體中,都可以使用 break 關鍵字終止整個循環體的運行。尤其是在和 if 的搭配使用中,當滿足某個條件時,就終止整個循環結構。

while True:
    username = input("輸入用戶名")
    paword = input("輸入密碼")
    if username == 'admin' and paword == '123456':
    	print('login')
    	break

continue

continue 則可以跳過本輪循環,進入下一輪循環。他也常常和 if 搭配使用:

songs = ['傳奇','', '禮物', '故鄉', '']
for song in songs:
	if not song:
	print("下一曲")
	continue
print(f"正在播放:{song}")

循環的自動化測試實際使用

自動化測試場景:表示多個測試數據

1、寫一個程序,存儲一個測試數據

username = input("請輸入用戶名:")
pass = input("請輸入密碼:")
age = input("請輸入年齡:")

user = dict()
user.update(username=username,
pass=pass,
age=age)

2、寫一個程序,可以存儲多個測試數據

users = list()
users.append(user)
print(users)

3、添加多個用例,運行多個用例

users = list()
while len(users) < 3:
    username = input("請輸入用戶名:")
    pass = input("請輸入密碼:")
    age = input("請輸入年齡:")

    user = dict()
    user.update(username=username,
                passd=pass,
                age=age)
    users.append(user)
    print(users)

    for case in users:
        print(f"運行用例-用戶名{case['username']}")

剛接觸循環,可能很難分析出代碼接下來會執行哪一行,此時可以在循環體內設置一個斷點,通過 debug 模式運行程序,從而理解代碼的執行過程。

練習題

練習題1:生成 0-100 的奇數怎麼寫?

練習題2:求出 0-100 的數的和?

練習題3:求出 0-100 的數的奇數和與偶數和

練習題4:生成一個 * 組成的直角三角形

練習題5:把 c 變成一個扁平的列表

while True:
    try:
        n=int(input())
        nums=[int(i) for i in input().split()]
        a = []
        if len(nums)==0:
            print(0)
            for i in nums:
                position = bisect.bisect_left(a, i)#在a中插入i應插入的位置index,排序;若i已存在,則返回左邊的位置index
                if len(a)==position:#第一個元素,或者大於a中元素的元素才插入
                    a.append(i)
                else:
                    a[position]=i#否則替換對應index的值
                    print(len(a))
                    except:
                        break
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章