# 3.2 while迴圈 Python中的while迴圈語法為: ```python= while 條件: Body of while # 放要執行的東西 ``` 舉個例子,這裡來印出1到10再把他們加起來: ```python sum = 0 i = 1 while i <= 10: print(i) sum = sum + i i = i + 1 print(sum) (輸出) 1 2 3 4 5 6 7 8 9 10 55 ``` 如果要讓它一直執行下去的話,可以用: ```python while 1: #判斷條件值為1, 代表迴圈永遠成立 print("muda") ``` ![img](https://gblobscdn.gitbook.com/assets%2F-MDZ74LOQcDUA3PMmePS%2F-MIIHewIVirXOSoErVIl%2F-MIIIdsyeQdTyFet2RoP%2Fezgif.com-video-to-gif%20(4).gif?alt=media&token=ea116b15-0348-40fb-be8e-cf809a16c423) 那麼,我們使用之前教的範例: [https://streamable.com/hqc7mm](https://streamable.com/hqc7mm)) 我們可以用以下程式紀錄他的台詞: ```python= i = 1 while i<=10: print("muda") i = i + 1 ``` while迴圈也可以放在一起,形成巢狀迴圈 舉例來說: ![img](https://gblobscdn.gitbook.com/assets%2F-MDZ74LOQcDUA3PMmePS%2F-MIIHewIVirXOSoErVIl%2F-MIIICBLh7ceIM66WcOz%2Fezgif.com-video-to-gif%20(2).gif?alt=media&token=ac9b737c-39b7-4ef2-9567-cd165dc67969) ```python= x = 0 while 1: print('pose '+str(x)) x = x+1 i = 1 while i<=10: print("muda") i = i + 1 ``` break和continue也還在,概念也差不多: https://streamable.com/w261wu ```python= x = 0 while 1: if x==1: break print('pose '+str(x)) x = x+1 i = 1 while i<=10: print("muda") i = i + 1 ``` tinue: ![img](https://gblobscdn.gitbook.com/assets%2F-MDZ74LOQcDUA3PMmePS%2F-MIIHewIVirXOSoErVIl%2F-MIII5nDylzTG_Nh9Tx1%2Fezgif.com-video-to-gif%20(1).gif?alt=media&token=d9cce945-daea-45eb-9d0f-73c8ee2fbcc3) ```python= x = -1 while 1: x = x+1 #記得把這一句放前面才不會無限循環 if x == 1 : continue #跳過pose1() print('pose '+str(x)) i = 1 while i<=10: print("muda") i = i + 1 ``` ## 基礎題: 請用上面的方式,使用continue和break,以程式碼打出下面這段gif的程式,並在muda了123次後結束迴圈。 ![img](https://gblobscdn.gitbook.com/assets%2F-MDZ74LOQcDUA3PMmePS%2F-MIIHewIVirXOSoErVIl%2F-MIIHuqqzYKfYM_NrktL%2Fezgif.com-video-to-gif.gif?alt=media&token=ae2e843e-821a-4577-a39b-a2984c0de595) ## 進階題(出自2020年10月APCS) 有一個公司有 n 個員工,還有兩個工廠。如果工廠一與工廠二分別有 X1 與 X2 個員工,兩個工廠的收益 Y1,Y2 分別會是 Y1=A1×X2平方+B1×X1+C1 Y2=A2×X2平方+B2×X2+C2 請你考慮所有分配員工的方式,找出收益最大的組合,輸出最大收益。 注意,每個員工皆需分配到其中一個工廠。收益可能為負數或0。 | 輸入說明 | 輸出說明 | | ------------------------------------------------------------ | ------------ | | 輸入說明第一行有三個整數 A1,B1,C1第二行有三個整數 A2,B2,C2第三行有一個正整數 n (1≤n≤100) | 輸出最大收益 | | 範例輸入 #1 | 範例輸出 #1 | | -------------- | ----------- | | 2 -1 34 -5 2 2 | 11 | ## 解答 ```python= a1=int(input()) b1=int(input()) c1=int(input()) a2=int(input()) b2=int(input()) c2=int(input()) n=int(input()) profit=a1*n*n+b1*n+c1 for i in range(n): if a1*i*i+b1*i+c1+a2*(n-i)*(n-i)+b2*(n-i)+c2>profit: profit=a1*i*i+b1*i+c1+a2*(n-i)*(n-i)+b2*(n-i)+c2 print(profit) ```