Search code examples
pythonpython-3.xsumrangearithmetic-expressions

sum the range of two inputs[python 3]


This script will accept two whole number inputs . first input will always be (-) than the second. script will display sum of every other whole number inputs.

script will not print any other text to the console other than the result of the operation.

here's the code i've written - so far i'm able to accept input but it produces an infinite loop and doesn't sum.

thanks

if __name__ == "__main__":

# user inputs digits
start = int(input())
stop = int(input())

# sum the range of above
while start < stop:
    print(sum for i in range(start, stop, 2))

Solution

  • In your problem start will always be less than stop, so the while loop never exits. Instead you can keep a variable that starts at start and increments by 2 until reaching stop.

    # user inputs digits
    start = int(input())
    stop = int(input())
    
    i = start
    total = 0
    while i < stop:
        total += i
        i += 2
    

    For conciseness, this can simply be done with

    total = sum(range(start, stop, 2))