How to make the program recognize a name with spaces next to a float?

Asked

Viewed 32 times

0

Code:

compras = {}
soma = 0
while True:
    dados = input().split()
    if dados[0] == '*':
        break
    else:
        compras[dados[0]] = float(dados[1])
while True:
    comandos = input().split()
    if comandos[0] == 'total':
        break
    if comandos[0] == 'quantidade':
        print(len(compras))
    elif comandos[0] == 'retire':
        del compras[comandos[1]]
for n in compras.values():
    soma += n
print(f'{soma:.2f}')

Entree:

brinquedos 130.57
brincos 55.60
vestido de grife 1900.90
*
quantidade (retorna 3)
retire brincos (irá deletar o objeto do dicionário)
quantidade (retorna 2)
total (acaba a entrada)

Exit:

3
2
2031.47 (soma dos valores que ficaram no dicionário)

I would like to know how to make the program read a composite name and not just unique names.

1 answer

4


Instead of

dados = input().split()

use the rsplit

dados = input().rsplit(maxsplit=1)

This will cause the user input to be divided from right to left, dividing only once - so all words will be in dados[0] and the float in dados[1]

Similarly, as your commands have only one word, use:

comandos = input().split(maxsplit=1)

To divide the command of your parameter, from left to right.

  • Thank you very much, I didn’t know this maxsplit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.