0

I am making a program that calculates the sum of all even and odd numbers between two number which are user inputted. I'm new to Python and am not sure how to use the range in a loop to make my program work. Here is my code. I know its sloppy and not well put together and not finished but any help works thanks.

n = int(input(" please enter a number"))
m= int(input(" please enter another number"))
count =0
sum =0
for x in range(n,m+1,2):
    if x%2==0:
        count=count+x
    sum = count
    print(" the total sum of odd numbers are",sum)
3
  • 1
    you are not testing if I input odd or even numbers. Your range only takes every 2nd number so the x%2 == 0 test is not needed - you only ever have odd OR even numbers depending on what you start with. Dont use sum as variable name, there is already a built in function called sum - you are shadowing it. If you want to sum values you can do : print(sum( range( 10,21,2) ) ) and get the result of 10+12+14+16+18+20 Commented Nov 4, 2018 at 21:32
  • calculates the sum of all even and odd numbers between two number : Does it means you do 2 sums, one for even numbers and other for odd numbers? Commented Nov 4, 2018 at 21:32
  • @emi yes i am calculating 2 sums Commented Nov 4, 2018 at 21:43

3 Answers 3

1

It's important to know if n is greater than m and invert situation if so. Other than that, you need to know if the smallest number is odd or even and begin the two ranges accordingly:

n = int(input("Please enter a number: "))
m = int(input("Please enter another number: "))

# n will always be the smaller one
if n > m:
    n, m = m, n

n_is_odd = n % 2 # Gives 1 if n is odd

n_even = n + n_is_odd # Sum 1 if n is odd
n_odd = n + (not n_is_odd) # Sum 1 if n is even

print("the total sum of even numbers is %d" % sum(range(n_even, m+1, 2)) )
print("the total sum of odd numbers is %d" % sum(range(n_odd, m+1, 2)) )
Sign up to request clarification or add additional context in comments.

2 Comments

confused on what tmp is
A temporal variable to swap n and m values. Fixed with list assignment.
0

Input validation is a big part of good coding. A good overview can be found here:

To make the validation it reusable I put the validation in a function that only accept integers and (if a minval is provided, makes sure that the input is bigger that the minval.

def while_invalid_ask_input_return_integer(text, minval = None):
    """Aks for input until a number is given that is > minval if minval not None
    returns an integer."""
    while True:
        c = input (text)
        try:
            c = int(c)
            if minval is not None and c < minval:
                raise ValueError  # its too small, raise an erros so we jump to except:
            return c
        except ValueError:
            if minval is not None:
                print("must be a number and greater ", minval)
            else:
                print("not a number")

I use it to get the first number, and the second number gets the first one as "constraint" so it will be bigger. For summation I just use the range starting once with n once with n+1 till m and a range step of 2. I check what even/oddness n has and print text accordingly:

n = while_invalid_ask_input_return_integer("please enter a number ")
m = while_invalid_ask_input_return_integer("enter number bigger then {}".format(n),n)

print( "Odd sum:" if n % 2 == 1 else "Even sum:", sum(range(n,m+1,2)) )
print( "Even sum:" if n % 2 == 1 else "Odd sum:", sum(range(n+1,m+1,2)) )

Output:

please enter a number k
not a number
please enter a number 55
enter number bigger then 55 2
must be a number and greater  55
enter number bigger then 55 150
Odd sum: 4896
Even sum: 4944

Doku:

Comments

0

Here's a function I think fits into the description of what you asked above. It returns None if the user doesn't enter the type of query he or she wants.

So query can either be odd or even and depending on this, it calculates the sum that you want. The function makes use of list comprehension which is super cool too.

def calculate_odd_or_even_sum(query):
    start = int(input(" please enter a number"))
    end = int(input(" please enter another number"))
    count = 0

    if query == 'even':
        return sum([x for x in range(start, end) if x % 2 == 0])
    elif query == 'odd':
        return sum([x for x in range(start, end) if x % 2 != 0])
    else:
        return 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.