Errors, Validation, and Debugging · practice
Validate Before Converting
Before int() converts text, a program can check the form it expects. This lesson accepts ordinary keyboard digits from 0 through 9, and the .isdigit() is a simple first check for that deliberately narrow requirement.
Consider a seat-number prompt:
while True:
answer = input("Seat number: ")
if answer.isdigit():
seat = int(answer)
break
print("Please enter digits only.")
print(f"Seat: {seat}")
The order matters:
input()produces a string..isdigit()validates that string.int()runs only after validation succeeds.breakleaves thewith a valid integer.
If the answer is invalid, the conversion is skipped. The message is printed, and the next loop iteration asks again.
Trace two attempts
If the answers are front and then 12, the flow is:
| Attempt | answer.isdigit() | Action |
|---|---|---|
"front" | False | print the guidance and repeat |
"12" | True | convert to 12 and leave the loop |
The program never sends "front" to int(), so that input cannot cause a
Validate the rule you actually need
For the ordinary 0 through 9 input used here, .isdigit() accepts examples such as "0" and "27". It rejects:
negative numbers such as
"-2";decimals such as
"3.5";signs such as
"+4";words such as
"many".
An empty string also fails this check. Surrounding spaces fail too, because this example does not strip the answer.
This exercise uses ordinary keyboard characters. Some other digit characters, such as "²", pass .isdigit() but still cause int() to raise ValueError. So .isdigit() is a useful first check here, not a guarantee that every possible string can be converted.
That is useful when the requirement really is digits only within this limited input set. It is not a complete test for every int() can understand. The next lessons introduce try and except, which can ask Python itself whether an integer conversion works.
Give actionable feedback
An error message should help the learner or user make a valid next attempt. “Invalid” is vague. “Please enter digits only.” states the expected format.
Keep the prompt inside the loop. Otherwise the program may repeat its check forever without collecting a new answer.
The user enters many and then 3. How many times does this program call int()?
while True:
text = input("Count: ")
if text.isdigit():
count = int(text)
break
print("Digits only.")
Task
Build a retrying ticket-count prompt. For this exercise, answers use ordinary keyboard characters and valid answers contain only 0 through 9. Use .isdigit() to check each answer before conversion.
On every attempt, prompt with:
Number of tickets:
If the answer contains anything other than digits, print:
Please enter digits only.
Then ask again. Once the answer is digits only, convert it to an integer, leave the
Tickets: 7
The prepared test data enters many, then -2, then 7. Your program must reject the first two answers without attempting to convert them.