0%

Errors, Validation, and Debugging · practice

Retry with try and except

A conversion can return None, but an interactive program often needs a valid answer before it can continue. Combine a with 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:

  1. int(text) raises ;

  2. Python jumps to except ValueError;

  3. the program prints useful guidance;

  4. continue starts the next loop iteration.

On valid integer text:

  1. conversion succeeds;

  2. the handler is skipped;

  3. break leaves 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 .

Input text goes to int conversion; ValueError prints guidance and continues to another attempt, while success records the integer and breaks out of the loop.

Why this accepts more than .isdigit()

The program asks int() whether conversion works. It therefore accepts such as:

"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 too. The chapter project will do exactly that.

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 that keeps asking until the user enters an integer.

Prompt with:

Enter an integer: 

When conversion raises , print:

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.