-1

I'm a newbie on Python programming, and I'm testing some features that I've learned so far. I wanted to create a program that helped me opening the cashier in the morning. I wrote a script that assings a string content to a n variable, so it tests first (with a while loop) if the user typed an alphabetic input. If so, it tells the user that one needs to type a numeric value and calls the input again, to be filled with a string value again. If it's not an alphabetic input, it exits this while loop. Now's the problem. I want it to ask for the user to keep typing numeric (float) values until one wants to exit this module, and then the sum is shown on screen. Inside this while loop, I put a conversion line from string to float, so it can sum the numbers and not only concatenate them together as a string. But I can't seem to make it work. This is the code so far

`n = input('n = ')
na = 0.00
while n.isalpha():
    print('Valor inválido. Insira um valor numérico.')
    n = input('n = ')
while n.isdecimal():
        n = float(n)
        na += n
        print('Insira o próximo valor: ')
        print('Digite qualquer letra para sair')
        n = input('n = ')
print('A soma é {:.2f}'.format(na))`

But then, if I type 5.22, for example, it exits the program without showing any errors:

    n = 5.22
A soma é 0.00

Process finished with exit code 0

How can I make this while loop work the way I want?

Ah, it works perfectly when I enter integer values on the n variable.

n = 5
Insira o próximo valor: 
Digite qualquer letra para sair
n = 5
Insira o próximo valor: 
Digite qualquer letra para sair
n = 5
Insira o próximo valor: 
Digite qualquer letra para sair
n = 5
Insira o próximo valor: 
Digite qualquer letra para sair
n = 5
Insira o próximo valor: 
Digite qualquer letra para sair
n = m
A soma é 25.00

Thanks in advance!!

Prune
  • 76,765
  • 14
  • 60
  • 81

1 Answers1

0

isdigit() check if string has only digits 0-9, . You can try this:

n.replace('.','',1).isdigit()

more examples in How do I check if a string is a number (float)?

tiagohbalves
  • 174
  • 1
  • 8