Why does my "Try" in Python not work?

Asked

Viewed 329 times

4

x = int(input("Por favor, insira um número: "))
try:
    print(x != int)
except ValueError:
    print("Somente números.")

The mistake that gives is:

ValueError: invalid literal for int() with base 10: 'x'

I don’t know what to do so that Python gives me an error message when the user gives something other than number as information.

3 answers

8

You ask for the die and try to do the conversion (the function int() does this), and if the conversion is not possible (because the typed text is unsatisfactory to create an integer) an exception will be thrown (unfortunately the documentation is flawed and says nothing about it). If you want to do something when this occurs then you should capture the exception as you did in except, but capture will only occur in codes within the block try, which was not the case, so when the exception is thrown there is no capture and the application breaks. So do what you want:

try:
    print(int(input("Por favor, insira um número: ")))
except ValueError:
    print("Somente números.")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

And to be clear, Python is giving exactly one error message when the user types something other than a number. What you want is just the opposite, you want your code to give a message when it happens and not Python.

6


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)
  • 4

    Just remembering that there are several characters for which isnumeric returns True but error when converting to int, see here. At the end the best option even is the first: use logo int() and capture the ValueError

  • 1

    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

  • 1

    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

-3

Vincenslau if you want to save the input value in the variable x do as follows:

while True:
    x = input("Por favor, insira um número: ")
    try:
        x = int(x)
        break
    except ValueError:
        print("Somente números.")

and Happy New Year...

  • 2

    Why wear while would be better?

  • I’m deducing that if "the program " is printing a message ("Only numbers.") then the user should probably enter another value, which is valid, again and that’s what while does, more if you want, you can take while and the break and code will work as well.

  • 3

    Okay, but that wasn’t explained in the answer, it’s the same as a person who sells "soap powder" saying that his brand is the best because it cleans better ... that doesn’t say anything technically, of course most people are lazy and like to just listen "use it that works best" not knowing why it’s supposed to be better. If we are a community of programmers we have to explain the points and the "why" so that the answer can teach programming and so that it is no longer a code of "copy and paste that will work".

  • 3

    It is the typical case of misunderstanding and lack of good faith in understanding a simple comparative, soap powder is an example to exemplify the problem, usually who does not like comparative to exemplify something is that has problems in accepting constructive criticism, is what I did, I gave you a share, you must have good will and understand that something needs to be improved and that we are not a technical support site nor Ctrl+c, we are a site that we seek to teach programming, in your comment you explained the "why" lack explain in the question, then put your ego aside and take a hint.

  • 3

    ps: the downvotes are not mine, but if only add your comment in BODY REPLY, using the edit button I will give you +1 as a sign of good faith on my part, to stay against the downvote q received. As I said, they are constructive criticisms, if you consider a good dev and want to evolve should accept them or at least analyze to make sure that you can or can not improve in certain points, whether as a person, as a professional, or as a programmer.

  • 2

    I understand the point and point of view of @Guilherme Nascimento and agree with him, his answer is not incorrect, it is correct and working, so it is a valid answer and does not deserve the downvotes, However, what he is trying to say is simply to improve our answers so that they serve others and help the learning, avoiding that create content of copy and glue, something that we disagree a lot. The only thing he’s guiding is to create explanatory content and not just pass the answer

  • As many people say, the python code itself is already self-explanatory and even more so in small code like this one. I went....

  • 3

    Many then mispronounce the self-explanatory, one thing is the native "Apis" and lingaguem syntax are comprehensive, another thing are the algorithms" created with codes, so who commented or commented wrong about being self-explanatory or commented on the "syntax of language" and not about the algorithms written with such language and you misunderstood what they meant about "self-explanatory".

  • 2

    The code can even be "self-explanatory" for those who already know the language. But by the question you can see that the person does not know (and nothing wrong with that, after all that is why she asked). And as the person does not know, then an explanation, however simple, is necessary (see the other answers, for example).

  • I’m in the mood to upvote on this answer but I can’t. There’s no explanation as to why while to know programming logic makes sense, but for those who are starting and coming from a google search and parachute landing here is not very intuitive.

Show 5 more comments

Browser other questions tagged

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