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.
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)
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)
Axios in a Node.js container on Kubernetes is returning “ECONNREFUSED 127.0.0.1:30561”?
Property 'map' does not exist on type 'Observable<Object>'.ts(2339)
How to make trim() function work in node.js code, even if not used in mongoose's model schema?
Hi I am working on AWS CDKI am trying to create policy
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
I have theese fields(test_type, status, begin_time, and_time)The status field has three state(0, 1 or 2)
I am using python's warning module with "with" statement :