Python循環求和通常使用for循環來實現,例如:
numbers = [1, 2, 3, 4, 5]
sum = 0
for num in numbers:
sum += num
print("Sum:", sum)
這段代碼會計算列表中所有數字的和,并輸出結果。您也可以使用while循環來實現相同的功能,例如:
numbers = [1, 2, 3, 4, 5]
sum = 0
index = 0
while index < len(numbers):
sum += numbers[index]
index += 1
print("Sum:", sum)
這段代碼也會計算列表中所有數字的和,并輸出結果。無論使用for循環還是while循環,都可以實現對列表中數字的求和功能。