1. 程式人生 > >for和while循環小練習

for和while循環小練習

() code 代碼 += 但是 app count while 都是

用for和while循環,對數字列表/數字元組中的元素進行求和:
用for實現
>>> val = 0
>>> l1 = [1,3,5,7,9]
>>> for i in l1:
... val +=i
...
>>> print(val)
25

用whlie實現
list1 = [1,3,5,7,9]
val = 0
count = 0

while count < 5:
val +=list1.pop()
count+=1

print(val)

用while感覺很復雜!!!可能有更簡單的方法,只是我不會 ^_^

修改需求:
由用戶輸入5個數字來組成列表
這個需求後面的求和與上面的相同,但是要實現用戶只能輸入5個數字,代碼如下:

list1 =[]
count = 0
num = 0
sum_list1 = 0
while count < 5:
num = int(input(Enter a num:))
list1.append(num)
count +=1


for i in list1:
sum_list1 +=i

print("the sum of nums is %s" % sum_list1)

註意點:
input()函數獲取的都是str(),導致最後list1不是數字列表,所以在用戶輸入的時候直接調用int()函數來把字符串轉換成數字。

for和while循環小練習