Search code examples
pythonexceptiontry-catchstring-formattingf-string

How to use f-strings or format in except block?


Trying to write a formatted message in the except block to potentially show the user their entered input and why it's incorrect.

try:
    rows = int(input("How many rows of odd numbers? >"))
    zero = 10 / rows
except (ValueError, ZeroDivisionError):
    print(f"{rows} is not a valid answer.")

This however gives me this error:

NameError: name 'rows' is not defined

Anyway to accomplish what I'm trying to do?


Solution

  • You get an error because rows is still not defined when the exception is raised, but you could do something like:

    rows = input("How many rows of odd numbers? >")
    try:
        zero = 10 / int(rows)
    except (ValueError, ZeroDivisionError):
        print(f"{rows} is not a valid answer.")