0

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.

15th Aug 2020, 7:38 PM
Teo Ichim
Teo Ichim - avatar
5 Respuestas
+ 5
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
15th Aug 2020, 7:53 PM
Tibor Santa
Tibor Santa - avatar
+ 2
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 😀😀
15th Aug 2020, 8:27 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
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.
16th Aug 2020, 3:12 PM
Tibor Santa
Tibor Santa - avatar
+ 1
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.
16th Aug 2020, 2:05 PM
Teo Ichim
Teo Ichim - avatar
+ 1
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.🤗🤗
16th Aug 2020, 4:34 PM
Tomiwa Joseph
Tomiwa Joseph - avatar