Reputation: 1
How to find the sum of even numbers from entered N numbers? i tried the below code but cant find the required output.
n=int(input('Enter the number:'))
if(n<=0):
print('Enter a valid number')
else:
sum=0
count = 0
while(n>0):
for count in range (i % 2 ==0)
sum+=n
n-=1
print(sum)
Upvotes: 0
Views: 1573
Reputation: 140168
this was more or less solved in comments by passing a range
with step
to sum
. Most pythonic way:
sum(range(2,n+1,2))
In that particular case, this can be improved to use a simple math expression to reduce complexity
since the sum of integers from 1 to n is n*(n+1)//2
, the sum of even numbers is
the double, with n divided by 2 (n
is even here but it also works with odd numbers thanks to integer division) so:
n//2 * (n//2+1)
Upvotes: 1