简体   繁体   中英

Sum of even numbers in Python

At uni we had the following problem: Create a function that is expecting an argument (an integer n) and that is returning the sum of all positive, even numbers between 1 and n. I tried the following solution:

def even_sum(number):
    count = 0
    sum = 0
    while count <= number:
        if count%2 == 0:
            sum = sum + count
            count = count + 1  
    return sum

But Python would just keep on loading. Why doesn't it work? In the end, I found this alternative solution that did work

def even_sum(number):
    sum = 0
    for i in range(0,number+1,2):
        sum = sum + i
    return sum

But I still kept on wondering what the problem was with the first solution.

The problem is the indentation in the count = count + 1 line. You need to execute that instruction on the while, not inside the if condition, because that will lead to an infinite loop. To achieve that, place the line at the same indentation level as the while loop:

def even_sum(number):
  count = 0
  sum = 0
  while count <= number:
    if count%2 == 0:
      sum = sum + count
    count = count + 1  
  return sum 

To better understand what is going on here, take a look at the value of count with the old solution:

1
1
1
1
1
1

As you can see, count has a fixed value on each execution of the while loop because it only increments if it finds an even number, but when it falls on odd numbers, it never changes and causes that behavior.

Your count = count + 1 is indented underneath the if . So for odd numbers, you never increment the count and you end up in an infinite loop.

You could sum a generator expression instead if you want a faster solution:

def even_sum(number):
    return sum(i for i in range(0, number+1, 2))

Edit: Actually you can just sum range itself which is even faster:

def even_sum(number):
    return sum(range(0, number+1, 2))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM