0

I have to include a function in my code and so I wrote the code below but I do not know how to add all the even numbers between the two numbers entered by the user. It prints the even numbers only, it does not add them.

def sum_of_two_no(num1, num2):
    for evenno in range(num1, num2 + 1):
        if evenno % 2 == 0:
            print (evenno)
num1 = 0
num2 = 0

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number number: "))

sum_of_two_no(num1, num2)

For example: If the user entered 1 for the first number and 10 for the second number, the program displays the even numbers between 1 and 10, but it does not add them.

Ashley Smith
  • 29
  • 1
  • 1
  • 5
  • Possible duplicate of [Python: How do I add variables with integer values together?](https://stackoverflow.com/questions/45744364/python-how-do-i-add-variables-with-integer-values-together) – Fynn Becker Jan 27 '19 at 14:55

4 Answers4

1
def sum_of_two_no(num1, num2):
    sum=0
    for evenno in range(num1, num2 + 1):
        if evenno % 2 == 0:
            sum+=evenno 
    return sum

I assume you are in initial phase of learning. To get the sum you have to actually do something to store the sum. Just take a variable and sum up all those even numbers in it and then just simply return it.

Anonymous
  • 335
  • 1
  • 2
  • 17
1

Try the code

def sum_of_two_no(num1, num2):
    sum=0
    for i in range(num1,num2+1):
        if i%2==0:
            sum+=i
    return sum

print(sum_of_two_no(4,7))

The problem with your code was that it wasnt storing the value of even numbers it was only printing it

Hope it helps

Talha Israr
  • 654
  • 6
  • 17
1

The sum of all even numbers from 1 to n is given by the n:th triangular number: n(n+1)/2. Simularily, the sum of 2, 4, ..., 2n is n(n+1). Hence we can compute this in O(1) by

def sum_of_two_no(num1, num2):
    # fix boundaries
    num1 = num1 // 2 - 1   # We subtract sum of 2, 4, ..., num1 - 2
    num2 = num2 // 2       # We add sum of 2, 4, ..., num2

    # Compute upper sum - lower sum
    return num2 * (num2 + 1) - num1 * (num1 + 1)
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
0

Or you can just loop through the evens without checking:

def sum_of_two_no(num1, num2):
    mysum = 0
    for evenno in range(start=num1+num1%2, stop=num2+1, step=2):
        mysum += evenno
    return mysum

The num1%2 insures we start at the closest even number.

Or you can one-line it in a pythonic way:

evensum = sum([evenno for evenno in range(start=num1+num1%2, stop=num2+1, step=2)])
ComplexGates
  • 743
  • 8
  • 15