I would like to get the sum of only the odd numbers stored in array and it shall pass as argument to the function. Here is my code:
def sum_odd(arr):
sum = 0
for i in arr:
if(i%2==1):
sum =i
return(arr)
nums = (input("Enter 10 numbers: "))
arr = list(map(int, nums.split()))
print("The sum of all odd numbers is: ", sum_odd)
but when I print it only says:
The sum of all odd numbers is: <function sum_odd at 0x0000025BE2A37F70>
I would also like to try to input an error message if the user inputs beyond 10 numbers.
CodePudding user response:
First of all you should give your function an argument when you call it Second, inside your function you're returning the array not the result. I changed your code and here it is:
def sum_odd(arr):
ans = 0
for i in arr:
if i%2 == 1: # if it's odd.
ans = i # keep adding up
return ans
arr = [int(x) for x in input("Enter 10 numbers: ").split()]
print("The sum of all odd numbers is: ", sum_odd(arr))
Input:
Enter 10 numbers: 1 2 3 4 5 6 7 8 9 10
output:
The sum of all odd numbers is: 25
CodePudding user response:
Please change the following two things.
- The
sum_add
function needs to be called. That is, changesum_add
tosum_add(arr)
print("The sum of all odd numbers is: ", sum_odd(arr))
sum_add
function is returning the array itself instead of the sum. Please change fromreturn(arr)
toreturn(sum)
These changes should solve the issues here