user9421447
user9421447

Reputation:

Python: Adding odd numbers together from an input

Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:

import math

def oddsum(n):
    y=n%10
    if(y==0):
        return
    if(y%2!=0):
        oddsum(int(n/10))
        print (str(y),end="")
        print (" ",end="")
    else:
        oddsum(int(n/10))

def main():
    n=int(input("Enter a value : "))
    print("The odd numbers are ",end="")
    oddsum(n)
    s = 0

    while n!=0:
        y=n%10
        if(y%2!=0):
            s += y
            n //= 10

        print("The sum would be ",end=' ')
        print("=",s)
        return

main()

It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)

I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.

Upvotes: 1

Views: 1629

Answers (3)

K.Marker
K.Marker

Reputation: 129

As @Anthony mentions, your code forever stays at 156 since it is an even num.

I would suggest you directly use the string input and loop through each element.

n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'

Note that int(i)%2 will return 1 if it is odd.

Upvotes: 1

ScottieB
ScottieB

Reputation: 4052

The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.

More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.

And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:

total = 0
for c in '1567':
   c_int = int(c)
   if c_int%2!= 0:
      total += c_int
      print(c)

print(total)

Upvotes: 1

Joost
Joost

Reputation: 3729

1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.

Upvotes: 1

Related Questions