Python的新手,我觉得我使用的总和不正确?

时间:2012-09-05 22:11:01

标签: python arrays list sum

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的初学者,并且只做了大约一个月。谢谢!

3 个答案:

答案 0 :(得分:2)

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

您必须输入强制转换,因为您输入的是一个字符串。这应该可以解决问题。

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

答案 1 :(得分:0)

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

另外,raw_input返回一个字符串。在第一个示例中,您可以将其替换为“input”,它可以正常工作。

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

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

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

答案 2 :(得分: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))

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