Ashley Smith
Ashley Smith

Reputation: 29

How do I allow my program to add the sum of even numbers between two numbers entered by the user? USING PYTHON

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.

Upvotes: 0

Views: 2023

Answers (4)

ComplexGates
ComplexGates

Reputation: 743

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)])

Upvotes: 0

Jonas Adler
Jonas Adler

Reputation: 10759

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)

Upvotes: 1

Talha Israr
Talha Israr

Reputation: 660

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

Upvotes: 1

Anonymous
Anonymous

Reputation: 355

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.

Upvotes: 1

Related Questions