Issue
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.
Solution
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
Answered By - Thekingis007 Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.