If, your intention is to implement a code that allows the insertion of only values numerical, of the kind float and are in the closed interval [0, 180] you should pay attention to your decision structure - if block. In this case, the correct way to implement the if block would be:
if (x < 0) or (x > 180):
Something else, when you want to capture something exception, specify which one you want to capture. Since it is not a good practice of programming in Python 3.x, no longer specify the type of exception you want. In this case, your line in which you specify an exception should also display the exception type. This way, the code line would be:
except ValueError:
Note that this type of exception returns the exception that was caused by value error. Which, it seems, is the one that most fits your case.
If you want to keep an eye out for python styling, go to This link.
Finally, the improved and more efficient code would be:
while True:
try:
x = float(input('Digite um valor entre "0" e "180": '))
if (x < 0) or (x > 180):
print('O número precisa estar entre "0" e "180"!')
break
except ValueError:
print('O valor precisa ser um número real! ')
print(x)
Another thing, if you want to skip a blank line, in the display of your prints, just use "\n" before the phrases inside your prints.
And finally, to answer your question, if you want to understand a little how the Python rounding behaves visit Official documentation. I do not intend to go into technical details because I do not want to expand the post.
the
float
tends to round up numbers of this type. Consider usingDecimal
.from decimal import Decimal
andangulo = Decimal(input('Digite um valor entre 0 e 180: '))
. I hope it helps– Paulo Marques
Related: https://answall.com/q/5642/112052
– hkotsubo
This question and answer will help tbm https://answall.com/questions/274772/problema-com-ponto-floatingpython-3
– Evilmaax
And this one gives an explanation of the problem and shows the approach of different languages to the theme https:/0.3000000000004.com/
– Evilmaax
You need to study the language documentation, floating point problems are common in programming languages. Of course, if you try to understand if you really need all of these decimal places, it is worth going deep https://docs.python.org/pt-br/3/library/ions.html?highlight=float#float and https://docs.python.org/pt-br/3/library/stdtypes.html#typesnumeric
– Maicon Herverton