A2oz

How to Find the Sum of Even Numbers Between Two Numbers in Python?

Published in Python Programming 3 mins read

You can find the sum of even numbers between two given numbers in Python using a loop and conditional statements. Here's a breakdown:

1. Using a for loop and conditional statement:

This method involves iterating through all numbers between the given range and checking if each number is even. If it is, we add it to a running sum.

def sum_even_numbers(start, end):
  """
  Calculates the sum of all even numbers between start and end (inclusive).

  Args:
      start: The starting number of the range.
      end: The ending number of the range.

  Returns:
      The sum of all even numbers within the range.
  """
  sum = 0
  for num in range(start, end + 1):
    if num % 2 == 0:
      sum += num
  return sum

# Example usage
start_num = 1
end_num = 10
sum_of_evens = sum_even_numbers(start_num, end_num)
print(f"The sum of even numbers between {start_num} and {end_num} is: {sum_of_evens}")

2. Using a for loop and a step of 2:

This approach utilizes the range() function with a step of 2, directly iterating through only the even numbers in the given range.

def sum_even_numbers(start, end):
  """
  Calculates the sum of all even numbers between start and end (inclusive).

  Args:
      start: The starting number of the range.
      end: The ending number of the range.

  Returns:
      The sum of all even numbers within the range.
  """
  sum = 0
  for num in range(start, end + 1, 2):
    sum += num
  return sum

# Example usage
start_num = 1
end_num = 10
sum_of_evens = sum_even_numbers(start_num, end_num)
print(f"The sum of even numbers between {start_num} and {end_num} is: {sum_of_evens}")

3. Using list comprehension and sum() function:

This method combines list comprehension and the sum() function for a concise and efficient solution. It creates a list of all even numbers within the range and then directly sums the elements of the list.

def sum_even_numbers(start, end):
  """
  Calculates the sum of all even numbers between start and end (inclusive).

  Args:
      start: The starting number of the range.
      end: The ending number of the range.

  Returns:
      The sum of all even numbers within the range.
  """
  return sum([num for num in range(start, end + 1) if num % 2 == 0])

# Example usage
start_num = 1
end_num = 10
sum_of_evens = sum_even_numbers(start_num, end_num)
print(f"The sum of even numbers between {start_num} and {end_num} is: {sum_of_evens}")

These are just a few ways to find the sum of even numbers in Python. Choose the method that best suits your programming style and the specific context of your application.

Related Articles