寫一個 Python 程序,求 10 個數的和,跳過負數。在這個 Python 示例中,for 循環範圍允許輸入 10 個數字,if 條件檢查是否有負數。如果為真,continue 語句將跳過該數字,不將其添加到 posSum 變量中。
posSum = 0
print("Please Enter 10 Numbersto Find Positive Sum\n")
for i in range(1, 11):
num = int(input("Number %d = " %i))
if num < 0:
continue
posSum = posSum + num
print("The Sum of 10 Numbers by Skipping Negative Numbers = ", posSum)
這個 Python 程序找到 10 個正數的和,並使用 while 循環跳過負數。
posSum = 0
print("Please Enter 10 Numbersto Find Positive Sum\n")
i = 1
while(i <= 10):
num = int(input("Number %d = " %i))
if num < 0:
i = i + 1
continue
posSum = posSum + num
i = i + 1
print("The Sum of 10 Numbers by Skipping Negative Numbers = ", posSum)
Please Enter 10 Numbersto Find Positive Sum
Number 1 = 10
Number 2 = -12
Number 3 = 15
Number 4 = -24
Number 5 = 100
Number 6 = -90
Number 7 = 120
Number 8 = -34
Number 9 = 80
Number 10 = 70
The Sum of 10 Numbers by Skipping Negative Numbers = 395
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/298108.html