Home > Back-end >  Sum of even numbers in Python
Sum of even numbers in Python

Time:05-02

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. Thanks in advance! And for reading so far :)

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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))
  • Related