Adding positives in an interval using just while

1

I need to write a program using a loop ( while ) that receives two numbers as input, and can be positive or negative and not necessarily in ascending order, and the program should print the sum of all positive numbers in that range. I started the code by creating a list with all the values in the range, and I need to add the positive values. How to proceed? Is there a better way than creating a list?

a = int(raw_input())
b = int(raw_input())
if a < b:
    a,b = b,a
if b < a:
    a,b = b,a
y = range(a, b + 1)
    
asked by anonymous 19.03.2016 / 15:26

1 answer

1

I think there is no simpler and more readable form than using the sum function, since it was meant for that.

a = int(raw_input())
b = int(raw_input())

soma = 0

if a < b:
    soma = sum([numero for numero in range(a, b + 1) if numero > 0])
else:
    soma = sum([numero for numero in range(b, a + 1) if numero > 0])

I used a list comprehension here. Basically, I'm saying "the sum of all the numbers in the range greater than 0".

Without using sum and for , you can solve this:

a = int(raw_input())
b = int(raw_input())
menor = a
maior = b

if a > b:
    menor = b
    maior = a

soma = 0

i = menor
while i <= maior:
    if i > 0:
        soma += i
    i += 1
    
19.03.2016 / 16:03