Errors, Validation, and Debugging · practice
Retry with try and except
A conversion None, but an interactive program often needs a valid answer before it can continue. Combine a try and except:
while True:
text = input("Temperature: ")
try:
temperature = int(text)
except ValueError:
print("Enter a whole-number temperature.")
continue
break
print(f"Recorded: {temperature}")
Follow the two paths
On invalid text:
int(text)raises; Python jumps to
except ValueError;the program prints useful guidance;
continuestarts the next loop iteration.
On valid integer text:
conversion succeeds;
the handler is skipped;
breakleaves the loop.
Only the successful path reaches the final print.
This flow keeps the retry and success paths visible at once. Follow the red side back to a new input attempt; follow the green side through break to the recorded

Why this accepts more than .isdigit()
The program asks int() whether conversion works. It therefore accepts
"12"
"-7"
"+4"
It rejects strings such as:
"three"
"4.5"
This matches a requirement for any integer, including negative integers. If the program instead needs a non-negative value, conversion is only the first validation step. After conversion, check the numeric
Place break carefully
Do not put break immediately after input(). That would end the loop before a failed conversion can cause a retry.
Do not forget to collect a new answer inside the loop. Rechecking the same invalid string would create a program that never makes progress.
If your program keeps running without making progress, use Stop in the editor controls. Then trace the paths through your loop: an invalid answer should lead to a new input() call, and a valid answer should reach break or
What happens when this code runs?
text = "-5"
try:
number = int(text)
except ValueError:
print("Not an integer")
Task
Write a
Prompt with:
Enter an integer:
When conversion raises
That was not an integer. Try again.
Then collect another answer. When conversion succeeds, leave the loop and print:
Accepted: -7
The prepared answers are three, 4.5, and -7. Catch only ValueError. A negative integer is valid for this exercise.