最簡單的循環10次ide
#-*- coding: utf-8 -*- #Author = "zero" for i in range(10): print("loop:",i)
輸出:oop
loop: 0 loop: 1 loop: 2 loop: 3 loop: 4 loop: 5 loop: 6 loop: 7 loop: 8 loop: 9
需求一:仍是上面的程序,可是遇到小於5的循環次數就不走了,直接跳入下一次循環測試
for i in range(10): if i<5: continue #不往下走了,直接進入下一次loop print("loop:", i )
需求二:仍是上面的程序,可是遇到大於5的循環次數就不走了,直接退出spa
for i in range(10): if i>5: break #不往下走了,直接跳出整個loop print("loop:", i )
需求三:仍是上面的程序,可是每跳一個打印一個,打印完畢退出code
for i in range(0,10,2): print("loop ",i)
加斷點測試continue用法blog
for i in range(0,10): if i < 3: print("loop ",i) else: continue print("hehe......")
兩個for循環utf-8
for i in range(10): print("-------------",i) for j in range(10): print(j)
for i in range(10): print("-------------",i) for j in range(10): print(j) if j>5: break
總結:continue跳出本次循環,進入下一次循環,break結束當前當次整個循環。input
用for代替剛剛的猜年齡程序:it
age_of_oldboy = 28 for i in range(3): guess_age == int(input("guess age:")) if guess_age == age_of_oldboy: print("yes, you got it.") break elif guess_age < age_of_oldboy: print("think bigger!") else: print("think smaller......") else: print("you have tried too many times..funck off!!")
仍是猜年齡程序,要求每猜錯三次提示「還要不要繼續玩?」for循環
age_of_oldboy = 28 count = 0 while count < 3: guess_age = in(input("guess age:")) if guess_age == age_of_oldboy : print("yes, you got it.") break elif guess_age < age_of_oldboy: print("think bigger!") else: pirnt("think smaller......") count +=1 if count == 3 countine_confirm = input("do you want to keep guessing..?") if countine_confirm !="n": # 不等於「n」繼續循環 count = 0