![]() |
My function won't return the sum unless the last paramater is an odd number. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: My function won't return the sum unless the last paramater is an odd number. (/thread-13126.html) |
My function won't return the sum unless the last paramater is an odd number. - Maximuskiller78 - Sep-29-2018 Hi guys, I'm trying to return the summation of all even numbers, but the function won't return anything unless the parameter "y" is an odd number. def sumOfEvens(x,y): total = 0 while x <= y: if (x % 2 == 0): total = (total + x) elif (x == y): return total x = (x + 1) I fixed it by removing the elif statment. def sumOfEvens(x,y): total = 0 while x <= y: if (x % 2 == 0): total = (total + x) x = (x + 1) return total RE: My function won't return the sum unless the last paramater is an odd number. - ichabod801 - Sep-29-2018 You know, a for loop would be much better in that situation: def sum_evens(x, y): total = 0 for z in range(x, y + 1): if z % 2: total += z return total |