2012-10-06 34 views
0

这是我的代码(Python的3.2)如何在Python中多次添加相同的变量?

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 

我如何得到它加起来正常吗?

回答

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
+1

重新使用'total'更糟糕。 –

+0

@MarceloCantos D'oh,你是对的。纠正。 –

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) 
+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

+0

只是让你知道,我编辑你的答案之前,我意识到它只是反映了这个问题。不酷。抱歉。 –

相关问题