This exception is made when the string that you are trying to convert is not in a valid format. This happens when you use the comma as decimal separator, when the string is empty or has non-numeric characters, etc.
>>> float('3,14159')
Traceback (most recent call last):
File "main.py", line 1, in <module>
float('3,14159')
ValueError: could not convert string to float: 3,14159
>>> float('')
Traceback (most recent call last):
File "main.py", line 1, in <module>
float('3,14159')
ValueError: could not convert string to float:
>>> float('foo')
Traceback (most recent call last):
File "main.py", line 1, in <module>
float('3,14159')
ValueError: could not convert string to float: foo
If you are using the comma, you need to replace the comma with the dot.
>>> float('3,14159'.replace(',', '.'))
3.14159
In other situations, you will need to validate first before converting to float. If the string is empty or has invalid characters, you must treat directly in the source of values. There is no way to define a generic solution.
Other than that, it is interesting that you keep a pattern in the nomenclatures of your variables. By convention, Python uses the Snake case, using the underlining, _
, as a word separator. So instead of total_PreçoCusto
, prefer total_preço_custo
, as well as preço_custo
and preço_venda
.
It turns out that Python, as well as several other languages, accepts accents, cedilla and etc in variable names. Finally, the error described in the question does not refer to this.
– LipESprY
@Lipespry actually didn’t even say which error he found.
– Cadu
Read the title of the question.
– LipESprY
hello folks the error I found was this : could not Convert string to float: I changed the code, but it keeps popping up, help, pfvr: File "C: exdb pp.py", line 179, in itens_get self.totalcp = float(self.cp) * float(self.stock) Valueerror: could not Convert string to float:
– Lucas Costa
self.totalcp = float(self.cp) * float(self.stock) self.totalsp = float(self.sp) ? float(self.stock) self.profit = float(self.sp ) - (self.cp)
– Lucas Costa