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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.