- 1

Please explain how does this loop works

def evensum(n): c = 2 s = 0 i = 1 while i <= n: s += c # next even number c += 2 i = i + 1 return s

18th Nov 2019, 2:34 PM
Thakur Lion😎😎
Thakur Lion😎😎 - avatar
5 Réponses
+ 3
First, it works to confuse the reader because the variable names carry no meaning - and because all of the unnecessary whitespace. Then, what exactly is the function supposed to do? My guess is it's supposed to give you all the even numbers up to n (including n) added up. But that doesn't work, because i is used for the condition instead of the even number, and it's only growing by 1 while c is growing by 2. If you print out c within that loop, you will see that it climbs way beyond n. Here's a version with real names so that a person can actually understand what's going on, and without the variable i. def evensum(number): sum_ = 0 even_number = 2 while even_number <= number: sum_ += even_number even_number += 2 return sum_
18th Nov 2019, 3:15 PM
HonFu
HonFu - avatar
+ 3
HonFu I think the original code was meant to sum the first n even numbers.
18th Nov 2019, 5:05 PM
Russ
Russ - avatar
+ 1
Ah, okay, in that case, the i would make sense of course. :) The concept just felt a bit foreign to me. In that case let me offer a variation (still without i though): def evensum(number): sum_ = 0 even_number = 2 while number: sum_ += even_number even_number += 2 number -= 1 return sum_ What I'd definitely do though is what I said about the names and the whitespace. Sometimes you can use a single letter for a variable (like i for index or something), but if you only use random single letters all the time, nobody including yourself in a few weeks will be able to read the code. A line of space between functions or something will increase readability, but if you pull single statements apart so that I'll have to scroll to read a mini code, it doesn't really enhance readability.
18th Nov 2019, 5:46 PM
HonFu
HonFu - avatar
+ 1
Yeah, I should have said that I agreed with all your other points. It's up to you of course but, just for future reference, I wouldn't spend too much time composing answers for this guy. He never gives any hint of any gratitude or appreciation for people taking time to explain something to him, nor any indication of whether he's understood what you explained.
18th Nov 2019, 6:05 PM
Russ
Russ - avatar
0
Russ i understood this and very very thanku and also SORRY😅😅😅😅😅😅
19th Nov 2019, 8:22 AM
Thakur Lion😎😎
Thakur Lion😎😎 - avatar