PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to add only odd numbers inside an array in python?

 July 21, 2022     arrays, integer, python, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing