【发布时间】:2020-02-15 00:43:00
【问题描述】:
说明:创建一个要求用户输入一系列数字的程序。用户应该输入一个负数来表示系列的结束。输入所有正数后,程序应显示它们的总和。
我正在使用 Python 2,Python IDLE
我正在为这个分配使用一个while循环。到目前为止,我做了一个程序,当用户在 while 循环下输入一个正数时,收集该数字并继续添加它,直到用户输入一个负数。我正在尝试找到一种将第一个用户输入包含到程序中的方法。
print('This program calculates the sum of the numbers entered and ends
after inputting a negative number')
total = 0.00
number = float(input('Enter a number: '))
while number >= 0:
print('Enter another positive value if you wish to continue. Enter a
negative number to calculate the sum.')
number = float(input('Enter a number: '))
total = total + number
print('The sum is', total)
【问题讨论】:
-
不是用 total = 0.0 初始化 total,而是将 total 设置为第一个数字(就在 while 循环之前)。
-
第一个输入可能是一个负数,那么总数就会出错。用户可能希望在第一次输入时退出。
标签: python python-2.7 python-requests