mike
mike

Reputation: 1

How to iterate through elements of a decimal number in Python

I want to pass an Integer converted to Decimal in Python. Then I need to check each single digit in the Decimal number if it is odd or even. For example, if integer is 534(it can be any integer though), converted to decimal it is still 534. Now if I try to iterate through this decimal to check if 5 is odd or even, then 3 is odd or even and then 4 is odd or even. If all digits are even, then it is True otherwise False. When I try to iterate through decimal number, then I get an error "Decimal is not iterable" Anyway, I created a program which achieves this purpose but I need to convert Decimal to String. Since requirement is to use Decimal so I think my solution is probably not meeting the requirement.

Thanks in advance

Upvotes: 0

Views: 681

Answers (1)

Derek
Derek

Reputation: 2234

This is not as neat but as far as I've been able to test it, it seems to work.

A bug fix should remove excess 0's from fraction.

It's getting messy but I have to assume certain input errors will occur and filter them out. Like entering 1. or .1 or 1.1000 for example,


def find_Odd_Even(m):
    try:
        n = list(str( m ))
        if n.count(".") < 2:
            if n.count(".") == 0:
                n.extend([ ".", "0" ])
            elif n.index(".") == len(n) - 1:
                n.append("0")
            b = n.index(".")
            BB = "".join( n[ b+1: ] )
            while len(BB) > 1:
                k = BB.removesuffix("0")
                if k == BB:
                    break
                else:
                    BB = k
            AA = int("".join( n[ :b ] ))
            BB = int( BB )
            if AA&1 == 1 or BB&1 == 1:
                answer = f"{m} is an odd number"
            else:
                answer = f"{m} is an even number"
        else:
            answer = "Bad input"
    except Exception as err:
        answer = str(err)
    finally:
        return answer

while 1:
    m = input("Enter an decimal number: ")
    if m == "":
        break
    else:
        print(find_Odd_Even( m ))

Upvotes: 0

Related Questions