0

这是我的代码(Python 3.2)

Total = eval(input("How many numbers do you want to enter? "))
#say the user enters 3
for i in range(Total):
    Numbers = input("Please enter a number ")
#User enters in 1
#User enters in 2
#User enters in 3
print ("The sum of the numbers you entered is", Numbers)
#It displays 3 instead of 6

我如何让它正确加起来?

4

3 回答 3

3

只需快速而肮脏地重写您的行:

Total = int(input("How many numbers do you want to enter? "))
#say the user enters 3
Numbers=[]
for i in range(Total):
    Numbers.append(int(input("Please enter a number "))
#User enters in 1
#User enters in 2
#User enters in 3
print ("The sum of the numbers you entered is", sum(Numbers))
#It displays 3 instead of 6

我假设您使用 Python 3 是因为您的方式print,但如果您使用 Python 2,请raw_input使用input.

于 2012-10-06T23:22:00.237 回答
2

此代码将解决您的问题:

total = int(input("How many numbers do you want to enter? "))
#say the user enters 3
sum_input = 0
for i in range(total):
    sum_input += int(input("Please enter a number "))
#User enters in 1
#User enters in 2
#User enters in 3
print ("The sum of the numbers you entered are", sum_input)

一些评论:

  1. 对于样式和变量名,您应该坚持使用pep8 。具体来说,under_store用于变量名和函数名,以及CapWords类名。
  2. 这里的使用eval是有问题的。这篇文章很好地解释了为什么你不应该eval大多数情况下使用。
于 2012-10-06T23:21:22.180 回答
1

您需要在 for 循环之外声明变量,并在循环中继续向其添加输入数字..

numbers = 0
for i in range(Total):
    numbers += int(input("Please enter a number "))

print ("The sum of the numbers you entered are", numbers)
于 2012-10-06T23:21:25.613 回答