如何在python中多次添加相同的变量?

时间:2012-10-06 23:18:39

标签: python

这是我的代码(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

如何正确添加?

3 个答案:

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

答案 1 :(得分: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的使用在这里值得怀疑。 This article非常清楚地解释了为什么不应在most cases中使用eval

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