How do I check if there is a number in a string?

Asked

Viewed 66 times

1

notas = input('Digite uma nota de 0 à 10: ')
if notas.isnumeric() or 0 < notas < 10:
    print('Nota inválida!')

Guys, I want to check if what the user typed contains any number, I’m trying this way, but I’m not getting it. Can you help me?

1 answer

2


The function input returns a string.

So the first test works, because the method isnumeric belongs to the class str.

However, Python does not perform type conversion to make comparisons as certain languages do. Thus, as an object str (string) does not allow comparison of larger and smaller with integers (objects of type int), the second test generates an error.


The solution, anyway, is to convert the string for whole. Only you can do this in two ways:

  1. Only during the test;

    if nota.isnumeric() and 0 < int(nota) < 10:
    
  2. Right in the assignment;

    nota = int(input('...'))
    
    if 0 < nota < 10:
    

If you choose the second option, the class itself int will take care of converting the user’s text to an integer number. However, if the user enters something wrong, the class will throw an exception of ValueError, what can make the program stop, if you want it to run endlessly. From there, you would have to implement other language structures, in order to "mitigate" this error and show a custom message, being able to "continue" the execution.

If you choose the first option, you will be first ensuring that the text is a valid numeric value, only then convert it and test if it is between 0 and 10. That way, you’ll be avoiding an exception which can already be treated with a simple test, which is what you do, and can treat an invalid value just by placing a block else.

Anyway, it’s up to you.

  • Would you have some place where I could check the documentation or base that your line of reasoning my dear ?

Browser other questions tagged

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