这是我的代码(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
如何正确添加?
答案 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)
一些评论:
under_store
,对类名使用CapWords
。 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)