0
all_currencies = currency_api('latest', 'currencies')  # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']

while len(moedas_importantes) != 0:
    for codigo, moeda in all_currencies.items():
        if codigo == moedas_importantes[0]:
            cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
            texto += f'{moeda} ({codigo.upper()}) = R$ {cotacao}   [{data}]\n'
            moedas_importantes.remove(codigo)
            if len(moedas_importantes) == 0: break  # WITHOUT THIS LINE, GIVES ERROR

Why am I getting this error? the list actually runs out of elements, but the code only works with the if

1
  • what error? please clarify your question and what you are trying to do Commented May 8, 2022 at 21:41

1 Answer 1

1

You have a nested loop. The while loop is entered and then execution immediately starts in the for loop. Execution remains in the for loop for all elements in all_currencies.items(). Each time codigo is found at the beginning of moedas_importantes, that element is removed. Eventually you remove all elements from moedas_importantes, but you are still in the for loop and check if codigo == moedas_importantes[0]. At this point moedas_importantes is empty so you get an index error.

I think the below code will work without the nested loops. Note, this assumes all elements in moedas_importantes are also keys in all_currencies.

all_currencies = currency_api('latest', 'currencies')  # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']

while len(moedas_importantes) != 0:
    codigo = moedas_importantes[0]
    moeda = all_currencies[codigo]
    cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
    texto += f'{moeda} ({codigo.upper()}) = R$ {cotacao}   [{data}]\n'
    moedas_importantes.remove(codigo)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the help!! now i understand well. Your solution was even more efficient, it took +- 10% less time to do the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.