--- title: 迴圈 - Python 教學 description: 中興大學資訊研究社1101學期程式分享會主題社課 tags: Python --- ###### [Python 教學/](https://hackmd.io/7-LP9CyOThOdkEbq44FLvw) # 迴圈 > [name=Hui][time= 109,10,27] --- ## 前言 程式寫作時,我們常常需要重複執行某段程式,這時迴圈的使用就顯得很重要 當我們已知or可計算執行的次數時我們常用for迴圈 而當執行次數難以計算時,就比較適合用while迴圈 # for 用法: for (一物件) in (所有物件) : 簡單來說 就是 for "自己取的變數名稱" in "list,taple....": "你要執行的程式碼" PS:注意縮排 我們每次執行 都會從 後面的 list **依序** 拿其中一個元素對他做處理 Q:那我只是單純的想做100次呢? 那就用"range()" ## for 範例1 for 後面接一個 range() 如 ```python= for i in range(5): print(i) # 0,1,2,3,4 ``` ### range > class range(stop) > class range(start, stop[, step]) 用法 1. 單純設定一個停止的數 如range(30) ```python= # 0,1,2,3,4,....29 ``` 2. 設定開頭和結尾 如range(5,30) ```python= # 5,6,7,8,9,10...29 ``` 3. 設定開頭、結尾和每一次加多少(step) 如range(5,30,5) ```python= # 5,10,15,20,25 ``` 當然數字不一定是要正的,負的也行 ### 練習1 輸入:n 輸出:n 到 0 ex:10,9,8,7,6,....0, hint: ```python= x = int(input()) #輸入一個數字,並轉為整數的型態 print(x) #輸出一個數字 ``` ### 練習2 輸入:n 輸出:F1~Fn 的費氏數列 ex: input:6 output:1,1,2,3,5,8, input:8 output:1,1,2,3,5,8,13,21, 解答: ```python= n = int(input()) fb_list=[] for i in range(n): if i == 0 or i == 1: fb_list.append(1) else : fb_list.append(fb_list[-1]+fb_list[-2]) print(fb_list) ``` ### for 範例2 for 後面接一個list 舉例來說 ```python= list=[2,4,5,8,1,3] for x in list: print(x) # 2,4,5,8,1,3 ``` 當然,不一定要都是相同的型態 ```python= list=['gawr','gura',1,0,0,'!'] for x in list: print(x,end='') ``` ### 練習3 給定 ```python= list_A=[1,2,3,54,4,4,6,8] ``` 輸出: 兩倍的list_A ex: [2,4,6,108,8.....] ### 練習3.5 給定 ```python= list_B=[1,2,3,54,4,4,6,8] ``` 輸出: 新的list_C=list_B的反過來 ex: [8,6,4,4,54,3,2,1] >hint: Using "insert()" to add item in new list ### for 範例3 ~~防風林外還有防風林外還有防林~~ for 迴圈中當然也還能有for 迴圈 而要怎麼判斷屬於哪層的for迴圈則是看縮排 ```python= list_G=[['x1','x2','x3'],['y1','y2','y3'],['z1','z2','z3']] for dim in list_G: for pos in dim: print(pos) ``` 上面這 第一個 dim指的是 list 中的 list ```python= a=10 b=20 count=0 for i in range(a): for j in range(b): count += 1 #count = count + 1 print(count) ``` 猜猜看會輸出多少? 因為內層的 for 執行了20次count+=1 而外層的 for 執行了內層的 for 10次 所以20*10=200 ```python= a=10 b=20 count=0 for i in range(a): count+=1 for j in range(b): count+=1 print(count) ``` 那這樣是多少呢? ### 印星星 for 搭配 if ```python= a=int(input()) listA=['gura',1,0,0,'!'] for x in listA: print(x,end=' ') print('') for i in range(a): if i==(int)(a/1.5): for j in range(a+i+1): if j>=a-i and j<=a+i+1: print('*',end='') else: print(' ',end='') else: for j in range(a): if j==a-i: print('*',end='') else: print(' ',end='') for j in range(i+1): if j==i: print('*',end='') else: print(' ',end='') print('') ``` ### 練習4 (easy) 輸入 n 印出 n*n的正方形 ex: input=3 output= **\* \*\*\* \*\*\* ```python= a=int(input()) for i in range(a): for j in range(a): print('*',end='') print('') ``` ### 練習5(hard 題目我抄來的) 輸入 n 印出 所有小於n的質數 ex: input=15 output=2,3,5,7,11,13 ```python= a=int(input()) count=0 for i in range(a): for j in range(1,i): if (i%j)==0: count+=1 if count==1: print(i,end=',') count=0 ``` ### 練習6(hard) 輸入 n 印出 半徑為n的圓形 you may need [sqrt()](https://www.runoob.com/python/func-number-sqrt.html) and [round()](https://www.runoob.com/python/func-number-round.html) ```python= import math r=int(input()) count=0 for i in range(2*r+1): for j in range(2*r+1): if (i-r)**2+(j-r)**2<=r**2 and (i-r)**2+(j-r)**2>=r**2 : print('*',end='') else: print(' ',end='') print('') ``` ## while whlie 通常用於我們不知道做幾次,但是知道甚麼時候該結束的事件 ```python= a=2 while(a<4096): a*=a print(a) ``` 上面範例就是a一直平方直到a>=4096 ```python= a=1 k=' ' while(k): k=input() a+=1 print(a,k) print('--end--') ``` 這段程式碼則是會在k沒有輸入時停止 ### break (can also use in for loop) 在執行到一半時,如果我們希望能直接跳出迴圈則使用break ![](https://i.imgur.com/e11sqIL.jpg) break! ```python= a=1 k=' ' while(k): k=input() if k=='exit': break a+=1 print(a,k) print('--end--') ``` 上面程式在k==exit時會直接跳出while loop ### continue (can also use in for loop) ```python= a=1 k=' ' while(k): k=input() if k== 'pass': continue a+=1 print(a,k) if k=='exit': break print('--end--') ``` ### practice 01 input 整數n ,n>0 請輸出 n 的二進位數 ex: input:4 output:100 input:15 output:1111 ```python= a=int(input()) output='' while(a>0): output=str(int(a%2))+output a=a-(a%2) a=a/2 print(output) ``` ## 疑難雜症 ### for x in list?? 舉例來說 ```python= list=[2,4,5,8,1,3] for x in list: print(x) # 2,4,5,8,1,3 ``` 不過這邊的運算大概是這樣 ```python= list=[2,4,5,8,1,3] for i in range(len(list)): x=list[i] print(x) ``` . . . . ```python= a=[-1,2,-3,-4,5,6,7,-8,9,-10,11] for x in a: x+=10 print(a) ``` 對x的操作只影響x 不影響list . . . ```python= a=[-1,2,-3,-4,5,6,7,-8,9,-10,11] for x in a: if x<0: a.remove(x) print(a) ``` ```python= a=[-1,2,-3,-4,5,6,7,-8,9,-10,11] for x in a[:]: if x<0: a.remove(x) print(a) ``` 如果對list直接操做要注意是否會影響跌代的結構 <style>hr{display:none;}</style> # 補充 for 迴圈其實是呼叫一個迭代器 [Python進階技巧 (6) — 迭代那件小事:深入了解 Iteration / Iterable / Iterator / \_\_iter__ / \_\_getitem__ / \_\_next__ / yield](https://medium.com/citycoddee/python%E9%80%B2%E9%9A%8E%E6%8A%80%E5%B7%A7-6-%E8%BF%AD%E4%BB%A3%E9%82%A3%E4%BB%B6%E5%B0%8F%E4%BA%8B-%E6%B7%B1%E5%85%A5%E4%BA%86%E8%A7%A3-iteration-iterable-iterator-iter-getitem-next-fac5b4542cf4) 所以可以透過自訂迭代邏輯來客製化迴圈 ex: ```python= class MyIterator: def __init__(self): self.total_times = 0 self.index = 0 def add_times(self, times): self.total_times += times return self def __iter__(self): return self def __next__(self): self.index += 1 if self.index <= self.total_times: return self.index else: self.index -= 1 raise StopIteration my_iterator = MyIterator() for item in my_iterator.add_times(3): print(item) for item in my_iterator.add_times(3): print(item) for item in my_iterator: print(item) ``` # 挑戰? https://leetcode.com/problems/two-sum/ https://leetcode.com/problems/add-two-numbers/ https://leetcode.com/problems/climbing-stairs/