编写一个 Python 程序来寻找 10 个数字的和,直到用户输入正数。在这个 Python 示例中,for 循环允许用户输入 10 个数字,if 条件检查负数。一旦用户输入负值,条件将返回 true,break 语句将退出循环。
Sum = 0
print("Please Enter 10 Numbers\n")
for i in range(1, 11):
num = int(input("Number %d = " %i))
if num < 0:
break
Sum = Sum + num
print("The Sum of Positive Numbers = ", Sum)
这个 Python 程序找到 10 个数字的和,直到用户使用 while 循环输入正数。
Sum = 0
print("Please Enter 10 Numbers\n")
i = 1
while(i <= 10):
num = int(input("Number %d = " %i))
if num < 0:
break
Sum = Sum + num
i = i + 1
print("The Sum of Positive Numbers = ", Sum)
Please Enter 10 Numbers
Number 1 = 23
Number 2 = 90
Number 3 = 98
Number 4 = 56
Number 5 = 47
Number 6 = -90
The Sum of Positive Numbers = 314