如何在 except 块中使用 f-strings 或格式?

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

尝试在 except 块中写入格式化消息,以潜在地向用户显示他们输入的内容及其不正确的原因。

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

然而,这给了我这个错误:

NameError: name 'rows' is not defined

无论如何要完成我想要做的事情?

你得到一个错误,因为在引发异常时 rows 仍然没有定义,但你可以这样做:

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