从输入列表中添加元素

问题描述 投票:-2回答:1

[伙计们,只是一个关于从循环中添加元素的新问题。我想根据用户输入的数量来获取元素列表的总和,但是我真的不知道什么样的语法或任何使其仅显示列表总和的语法,我知道我只需要声明一个变量将其等同于列表的总和,但我真正的问题是如何从列表中获取元素的总和。

b=int(input("Enter the value of N: "))
for num in range (1,b,2):
    print("Sum of odd numbers from 1 to",b,"is",num)

输出:

Enter the value of N: 5
Sum of odd numbers from 1 to 5 is 1
Sum of odd numbers from 1 to 5 is 3

我需要的输出:

Enter the value of N:5
Sum of odd numbers from 1 to 5 is 9

由于1 + 3 + 5,我需要输出为9,这是我需要加总的奇数,来自列表。

python list
1个回答
0
投票

您应该添加数字,然后打印出来。

    b=int(input("Enter the value of N: "))
    sum=0
    for num in range (1,b+1,2):
        sum+=num
    print("Sum of odd numbers from 1 to",b,"is",sum)
© www.soinside.com 2019 - 2024. All rights reserved.