pythondictionaryenumerateforexcurrency-exchange-rates

Dictionary Iteration Won't run fully


so, i am trying to write code that allows you to 1) input a phrase 2)input a string with the currencies you want to convert from and to (e.g. USD EUR; EUR GBP) 3) exchange rate of those two.

if you put in "I had USD 300 and then I had USD 400," (1), "USD EUR" (2), and 4 (3), it should return "I had USD 300 (~EUR 900) and then I had USD 400 (~EUR 1600).

However, my code below only "converts" the first reference to USD (USD 300, but not USD 400), returning - "I had USD 300 (~EUR 900) and then I had USD 400". I am not sure what I am doing wrong. if you see an error in my code, please let me know! thanks in advance :)

phrase = "I had USD 300 and then I had USD 400"
currency = "USD EUR"
ratio = 4

if phrase and currency:
    z = phrase.split()
    for order,word in enumerate(z):
        dictionary = {order : word}
        for i in dictionary.values():
            if i == currency.split()[0]:
                firstplace = z.index(i)
                if currency.split()[1] not in z[int(firstplace) + 2]:
                    convertednumber = (int(float((z[int(firstplace) + 1])))) * int(float(ratio))
                    z.insert(int(firstplace) + 2, f'(~{currency.split()[1]} {convertednumber})')
                    emptyphrase = " "
                    phrase = emptyphrase.join(z)
                else:
                    pass
            else:
                pass

print(phrase)

P.s. I know this is not a particularly efficient way of doing this, but I am just trying to test things out :)


Solution

  • This works, but there are problems. The punctuation at the end of "400." gets used as part of the number. That's OK here, but it makes for an awkward sentence. But it can give you the basic idea.

    phrase = "I had USD 300 and then I had USD 400."
    currency = "USD EUR"
    ratio = 4
    
    new = []
    handle = False
    for word in phrase.split():
        new.append( word )
        if word == currency.split()[0]:
            handle = True
        elif handle:
            convertednumber = int(float((word))) * int(float(ratio))
            new.append( f'(~{currency.split()[1]} {convertednumber})')
            handle = False
    
    print(' '.join(new))