Adding elements from the inputted list

74
December 10, 2019, at 10:40 PM

Hey guys just a newb question about adding elements from the loop. I wanted to get the sum of the list of elements depending on the number the user inputted but I really dont know what kinda syntax or anything to make it display only the sum of the list, I know that I just have to declare a variable that equates it to the sum of the list, but my real question here is how to get the sum of the elements from the list.

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)

output:

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

output I need:

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

I needed the output to be 9 since 1+3+5, which are odd numbers are the ones I needed to be summed, which came from the list.

Answer 1

You should add the numbers and then print them.

    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)
Answer 2

If you want to make it quicker you can use the closed formula for the sum of the first n odd integers, i.e.

Then your program would look like:

b=int(input("Enter the value of N: "))
if b % 2 == 1:
    s = ((b+1)//2)**2
else:
    s = (b//2)**2
print('The sum of the odd integers from 1 to', b, 'is', s)
READ ALSO
Unable to write policy document in aws cdk using python

Unable to write policy document in aws cdk using python

Hi I am working on AWS CDKI am trying to create policy

70
How to use regex to extract a number from a URL using pandas

How to use regex to extract a number from a URL using pandas

I'm at a stage to extract the page number from a URL which I got from web scrapingThis page number I will use to make a loop

50
How can I make this query in Django?

How can I make this query in Django?

I have theese fields(test_type, status, begin_time, and_time)The status field has three state(0, 1 or 2)

67
AttributeError: __exit__ while after conversion from Python2 to Python3

AttributeError: __exit__ while after conversion from Python2 to Python3

I am using python's warning module with "with" statement :

78