Why does the last letter doesn't add up where it belongs?

i am pretty new to coding in python and we have some programs to make for class.
The program needs to split without slicing or other functions the first part of a digit -> 12.5 becomes 12 and 5. I have so managed to make this which works only for the first part and then the last digit doesn’t add up where it belongs. Could you explain me why?

def decoupage(nombre:str)->(str,str):
    partie_entiere = ''
    partie_decimale = ''
    delimiteurs = [',','.']
    compte = 0
    for lettre in nombre:
        if lettre not in delimiteurs:
            if compte != 1:
                partie_entiere += lettre
        elif compte == 1:
                partie_decimale += lettre
        else:
            compte += 1
    return partie_entiere, partie_decimale


assert decoupage("12.5") == ('12', '5')
assert decoupage("12,5") == ('12', '5')
assert decoupage("0.5") == ('0', '5')
assert decoupage("12") == ('12', '0')

Tried to execute the code line by line and then i saw the problem, 12 finishes where it belongs "partie_entiere" then "partie_decimale" doesn’t have 5 in it.

>Solution :

Try this?

def decoupage(word:str)->(str, str):
    entire_part = ''
    decimal_part = ''
    delimiters = [',','.']

    after = False
    for letter in word:
        if not after:
            after = letter in delimiters
            if letter not in delimiters:
                entire_part += letter
        else:
            decimal_part += letter

    if decimal_part == '':
        decimal_part = '0'
        
    return entire_part, decimal_part



assert decoupage("12.5") == ('12', '5')
assert decoupage("12,5") == ('12', '5')
assert decoupage("0.5") == ('0', '5')
assert decoupage("12") == ('12', '0')

Leave a Reply