简体   繁体   English

如何在 CodeHS 8.4.5: Five Numbers 上打印我所有数字的总和?

[英]How do I print the sum of all of my numbers on CodeHS 8.4.5: Five Numbers?

Using a for loop, ask the user for five numbers.使用 for 循环,向用户询问五个数字。 Store those numbers in a list.将这些数字存储在列表中。 Each time you add a new number to your list, print the list.每次向列表中添加新号码时,请打印该列表。 (Your list will initially be empty.) (您的列表最初是空的。)

You should report the sum of the numbers in the list at the end.您应该在最后报告列表中数字的总和。

An example run of your program might look like this:程序的运行示例可能如下所示:

Number: 3
[3]
Number: 6
[3, 6]
Number: 12
[3, 6, 12]
Number: 2
[3, 6, 12, 2]
Number: -5
[3, 6, 12, 2, -5]
Sum: 18

This is my code right now:这是我现在的代码:

my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print my_list
print "Sum: " + new_number*5

I almost have this code right.我几乎把这段代码弄对了。 There's just one problem: I need to print the sum.只有一个问题:我需要打印总和。 Right now, it's an error because I have a str and int object on line 6 and I need that fixed.现在,这是一个错误,因为我在第 6 行有一个strint对象,我需要修复它。

This is the error that it gives:这是它给出的错误:

Error: Line 6
TypeError: cannot concatenate 'str' and 'int' objects on line 6
my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print (my_list)
b= sum(my_list)
c=str(b)
print ("Sum: " + c)

Your code missed: brackets in line 5 for printing getting the sum for the list converting sum to string for final concatenation before printing in last line您的代码遗漏了:第 5 行中的括号用于打印获取列表的总和将总和转换为字符串以在最后一行打印之前进行最终连接

my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print my_list
print("Sum: " + str(sum(my_list)))

I replaced your last line in the code with the one in my previous comment, seems to be working fine, in both cases positive and negative numbers我用我之前评论中的那一行替换了代码中的最后一行,似乎工作正常,无论是正数还是负数

here is another way to do it,这是另一种方法,

sum = 0
for i in range(5):
    sum += int(input("Number: "))
print("Sum: " + str(sum))

Hope this helps!希望这可以帮助!

It is just this.就是这样。

num = 0
for i in range(5):
    new_number = int(input("Number: "))
    num+=new_number
    print num

Not that hard.没那么难。

my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print(my_list)
sum=my_list[0]+my_list[1]+my_list[2]+my_list[3]+my_list[4]
print ("Sum: " + str(sum))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM