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)
I thought about using 'sum' in the code I wrote, but I need to add only values greater than 0, using loop ('while')
– Guilherme Santana De Souza
Sorry. I didn’t read it right. I’m editing.
– Pablo Almeida
What does it mean '+='?
– Guilherme Santana De Souza
x += y
is a shorter way of writingx = x + y
. You can switch to the more extensive form if you find it clearer.– Pablo Almeida
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!
– Guilherme Santana De Souza
Which part specifically you’re talking about?
– Pablo Almeida
sum = sum([number for number in range(a, b + 1) if number > 0])
– Guilherme Santana De Souza
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.– Pablo Almeida
Indeed, it makes it much easier. Thank you!
– Guilherme Santana De Souza