The try
serves exactly for this, to launch an exception of yours without necessarily stopping the program, however, the way you are trying to use this incorrect, the line that throws the exception must be within the try
In your case you start trying to assign a value to x
using the input
, up ai beauty, but you want to convert it to a whole number using the int
In case if typed something it is not possible to convert to a whole number it throws the exception
To fix this problem you can use the try
, but remembering, it has to be inside the same, for example
try:
x = int(input("Por favor, insira um número: "))
except ValueError:
print("Somente números.")
From what I understand you wanted to put a condition for the error, however, the try
does not use condition and yes when an error is released
Bonus
If you want to throw an error using condition use the assert
An example using it with your code, remembering that it is an example with your code, but the best method is the top
x = input("Por favor, insira um número: ")
try:
assert x.isnumeric() and x.isascii() # O método "isascii()" funciona somente para as versões mais recentes do Python, porém, o uso dela seria para restringir a quantidade de caracteres para o determinado exemplo, para versões desatualizadas, pode fazer o uso de "ord()" no lugar dos dois.
# assert all([ord(d) in range(48, 58) for d in x]) # Para versões anteriores há essa opção onde irá restringir os números de 0 a 9
except:
print("Somente números.")
else:
x = int(x)
Just remembering that there are several characters for which
isnumeric
returnsTrue
but error when converting toint
, see here. At the end the best option even is the first: use logoint()
and capture theValueError
– hkotsubo
Yes and I agree, as I said above the first is more valid, however, the boy’s code, if you analyze you will see that he tried to use a condition, something that the Try does not use and just wanted to show how it works when you want to use condition to return an exception, is just a demonstration and teaching of how the Try and the assert works
– Guilherme França de Oliveira
But thank you for the remark, I will correct by restricting a little more the characters for this example, but unfortunately it will be valid for the latest versions of Python that now I do not remember which version exactly
– Guilherme França de Oliveira