2.4 迴圈
For Loop迴圈
結尾需要有:
# Program to find the sum of all numbers stored in a list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # iterate over the list sum = 0 for val in numbers: sum = sum + val print("The sum is", sum) # The sum is 55
For loop with range()
# range(stop) # range(start, stop[, step]) numbers = [1, 2, 3, 4, 5, 6] # iterate over the list using index for i in range(len(numbers)): print("number", numbers[i]) # iterate over the list using 2 steps for i in range(0, len(numbers), 2): print("2 steps", numbers[i]) # Output number 1 number 2 number 3 number 4 number 5 number 6 # Output 2 steps 1 2 steps 3 2 steps 5
For loop with enumerate( )
取得迴圈目前的索引值
pets = ('Dogs', 'Cats', 'Turtles', 'Rabbits') for index, pet in enumerate(pets): print(index, pet) # Output: 0 Dogs 1 Cats 2 Turtles 3 Rabbits
While Loop
n = 10 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum) # The sum is 55
Nested Loop
for i in range(0, 2): for j in range(0, 2): print("i=", i, "j=", j, ", i*j=", i*j) # Output: i= 0 j= 0 , i*j= 0 i= 0 j= 1 , i*j= 0 i= 1 j= 0 , i*j= 0 i= 1 j= 1 , i*j= 1
break, continue and pass
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # break for val in numbers: if val >= 4: break print(val) # Output 1 2 # pass 3 for val in numbers: pass # continue for val in numbers: if val >= 3 and val <=8: continue print(val) # Output 1 2 9 10
List comprehension
用迴圈快速產生串列
# make new lists by using iterable squares = [] for x in range(10): squares.append(x**2) print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # equivalently squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
迴圈內加入判斷式產生串列
# with if squares = [x**2 for x in range(10) if x % 2 == 0] print(squares) ## [0, 4, 16, 36, 64] # equivalently squares = [] for x in range(10): if x % 2 == 0: squares.append(x**2) print(squares) ## [0, 4, 16, 36, 64]
Test
Q2. 給予一個列表,計算出列表中元素為 2的倍數的和。 Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Expected Result : 30
list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] tot=0 for index,num in enumerate(list): if(index%2==1): tot+=num print(tot)
Q3. 輸入人物的身高、體重,計算出該人物的 BMI 公式:BMI = 體重(公斤) / 身高*身高 (公尺) P.S. 於2002年4月公布臺灣成人肥胖標準: BMI<18.5 為過輕, 18.5≦BMI<24 為正常體重, 24≦BMI<27 為過重, BMI≧27 即為肥胖
weight=float(input('請輸入體重(kg)')) high=float(input('請輸入身高(m)')) bmi=weight/(high*high) print(type(bmi)) if bmi<18.5: print('過輕') elif bmi<24.0 and bmi>=18.5: print('正常') elif bmi<27 and bmi>=24: print('過重') else: print('肥胖')
Q4. 印出 1 到 50,但如果是 3 的倍數就印 Fizz,如果是 5 的倍數就印 Buzz,如 果同時是 3 和 5 的倍數就印 FizzBuzz。
for num in range(1,51): if num%3==0 and num%5==0: print('FizzBuzz ',num) elif num%5==0: print('buzz ',num) elif num%3==0: print('Fizz ',num) else: print(num)