0
input1 = raw_input("Hello enter a list of numbers to add up!")
lon = 0
while input1:
  input1 = raw_input("Enter numbers to add")
  lon = lon + input1
print lon

该程序应该添加所有给定的数字。它不起作用,所以我尝试列出一个列表:

input1 = raw_input("Hello enter a list of numbers to add up!")
lon = []
while input1:
  input1 = raw_input("Enter numbers to add")
  lon.append(input1)
print sum(lon)

它仍然不起作用?任何解决方案为什么?我是 Python 的初学者,并且只做了大约一个月。谢谢!

4

3 回答 3

2
input1= int(raw_input("Enter numbers to add"))

您必须输入 cast it,因为您输入的是一个字符串。那应该可以解决问题。

或者正如 Keith Randall 指出的那样,input("Enter numbers to add")改用它。

于 2012-09-05T22:13:42.643 回答
0

看起来您可能想在一个空输入上终止,因此您应该在尝试将其转换为 int 之前检查它

print "Hello enter a list of numbers to add up!"
lon = 0
while True:
    input1 = raw_input("Enter numbers to add")
    if not input1:
        # empty string was entered
        break
    lon = lon + int(input1)
print lon

如果用户输入了无法转换为 int 的内容,该程序将崩溃,因此您可以像这样添加异常处理程序

print "Hello enter a list of numbers to add up!"
lon = 0
while True:
    input1 = raw_input("Enter numbers to add")
    if not input1:
        # empty string was entered
        break
    try:
        lon = lon + int(input1)
    except ValueError:
        print "I could not convert that to an int"
print lon

同样,在您的程序的第二个版本中,您需要这样做

lon.append(int(input1))

您可以添加类似于上面显示的异常处理程序

于 2012-09-06T00:09:41.290 回答
0

首先,我假设您的缩进是正确的(while 循环内语句的制表符/空格) - 否则,您应该修复它。

此外,raw_input 返回一个字符串。在第一个示例中,您可以将其替换为“输入”,它会起作用。

在第二个示例中,您可以将字符串拆分为数字并将 sum 应用于它们,如下所示:

input1 = raw_input("Enter numbers to add")
lon.extend(map(int, input1.split()))

请注意,我使用了“扩展”而不是附加 - 否则,我会将数字列表作为列表元素添加到列表中,而不是用新数字扩展它。

于 2012-09-05T22:16:20.147 回答