Python: How to add numbers printed from a for loop from a specific range? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python: How to add numbers printed from a for loop from a specific range?

I already have the for loop that prints odd numbers from a specific range. But now I have to add all of these....and I just can't figure it out... :( Thanks for your advice!!

7th Nov 2019, 11:56 PM
broadenyourmindbnr
broadenyourmindbnr - avatar
3 Answers
+ 3
variable = 0 for loop start: conditions if any: variable += iterator print(variable)
8th Nov 2019, 12:08 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
You can use the sum() function and a comprehension print(sum(i for i in range(3, 20) if i % 2))
8th Nov 2019, 5:28 AM
David Ashton
David Ashton - avatar
+ 1
You set a variable to zero before the loop. And then, with every number of the range, you add that number to it.
7th Nov 2019, 11:57 PM
HonFu
HonFu - avatar