Adding up positives in a range using only while

Asked

Viewed 3,034 times

1

I need to write a program using loop (while) that receives two numbers as input, can be positive or negative and not necessarily in ascending order, and the program must print the sum of all positive numbers in that range. I started the code by creating a list of all the values of the range, and I need to add the positive values. How to proceed? There’s 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)

1 answer

1


I think it has no simpler and readable form than using the function sum, since she was made for it.

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 comprehensilist on here. Basically, I’m saying "the sum of all numbers in the range greater than 0".

Unused sum and for, you can solve like 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
  • I thought about using 'sum' in the code I wrote, but I need to add only values greater than 0, using loop ('while')

  • Sorry. I didn’t read it right. I’m editing.

  • What does it mean '+='?

  • x += y is a shorter way of writing x = x + y . You can switch to the more extensive form if you find it clearer.

  • I got it. I didn’t know I could write the line of code putting the conditional function at the end, or I had seen it before and I didn’t pay attention to the detail. Thank you!

  • Which part specifically you’re talking about?

  • sum = sum([number for number in range(a, b + 1) if number > 0])

  • This is a special syntax. What comes inside the keys is a comprehensilist on . It is an expression that generates a new list transforming the elements of another. You can apply this transformation only to elements that satisfy a-- condition for this if, that has to come at the end . Read more about it when you have time. It’s a very cool Python tool to make your code simpler.

  • Indeed, it makes it much easier. Thank you!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.