Table of Contents
Issue
I am trying to solve this function.
I have to create a tuple with the sum of the even and odd numbers of this list.
So the output should be (9,12) but my function doesnâ€™t work.
I do have to use a function
number_list = [1, 2, 3, 4, 5, 6]
def calculate_odd_even(odd_number, even_number):
odd_number = 0
even_number = 0
t1 = tuple()
for i in number_list:
if i % 2 == 0:
even_number = even_number + number_list[i]
t1.append(i)
else:
odd_number = odd_number + number_list[i]
t1.append(i)
return odd_number
return even_number
my_tuple = calculate_odd_even(odd_number, even_number)
Solution
You need some changes in your code:

No need for function arguments in this case.
:def calculate_odd_even(odd_number, even_number)
 +
def calculate_odd_even()
:

You iterating over the elements of list, not indices.So there is no need to use
number_list[i]
, justi
will do the
job.even_number = even_number + number_list[i]
odd_number = odd_number + number_list[i]
even_number = even_number + i
odd_number = odd_number + i

Second
retrun
wont be reached ever.So instead, return a tuple.

return odd_number retrun even_number # Wont be reached
return (odd_number, even_number) # currect way
Final code
number_list = [1, 2, 3, 4, 5, 6]
def calculate_odd_even():
odd_number = 0
even_number = 0
for i in number_list:
if i % 2 == 0:
even_number = even_number + i
else:
odd_number = odd_number + i
return (odd_number, even_number)
my_tuple = calculate_odd_even()
print(my_tuple) # prints (9, 12)
Answered By – AbbasEbadian
Answer Checked By – Mary Flores (BugsFixing Volunteer)