Entry Integer Validation | Sololearn: Learn to code for FREE!


Entry Integer Validation

How do I check with if and else statements that the entry input of a 'number question' is a number and not letters.

8/15/2020 7:38:46 PM

Teo Ichim

5 Answers

New Answer


Why do you want to use if/else? It is common in Python to use "duck typing" to validate if some data is a certain type. We follow the guideline: if it quacks like a duck, it must be a duck! How does that work? When we use input() we get a string. We try to convert it to number (integer) with error handling. If the conversion fails, we capture the ValueError and it is a good practice to also provide a default value, if the user gave wrong input. Here is it in action: https://code.sololearn.com/czEF9r3IgGLp/?ref=app


Teo Ichim You could also use string method isdigit() to know if everything in a string is a number Example: a = '123' print(a.isdigit()) Output: True The best solution and practice is to catch any possible error in a try and except block as Tibor Santa rightly stated. This way your program won't have to crash because of wrong input. Happy Coding 😀😀


Teo Ichim you are right, we can't understand if you don't explain properly the context. You never mentioned anything about forms and message boxes. So now I assume you are working on some sort of user interface, maybe with Django or Tkinter. It would be best to actually post your source code (at least the relevant parts) that would give some idea what you are trying to accomplish. And please add tags which library you are working with.


You guys don't seem to understand. I have a registration form with many entries, but for the Contact No. entry, I want it to show a messagebox.showerror if any letters are entered. If there are no letters and just numbers, it should keep running.


Teo Ichim Please take your time to frame your questions properly and use the right tags. Also, private chat me if this concerns tkinter. I know one or two things about it.🤗🤗