使用 String 而不是 Try/Except 可以防止崩溃 - 怎么做?

With using String instead of Try/Except prevent crashing- How to?

我正在为大学作业编写风寒指数代码。 教授希望我们在不使用 Try/Except 块的情况下防止代码在用户输入空白或字母时崩溃。 (他仅指字符串方法)。

与其崩溃,不如输出一条错误消息,例如。 ("invalid input, digits only")

我尝试使用 string.isdigit 和 string.isnumeric,但它不接受负数作为整数。

有什么建议吗? (下面的代码) 另一个 "if" 语句行得通吗?

使用无限循环并检查是否一切正常。 每当出现错误时,请使用 continue 语句。当所有检查和转换完成后,使用 break 语句。

import re
import sys
while True:
    print("Temperature")
    s = sys.stdin.readline().rstrip('\n')
    if re.match("^-?[0-9]+(\.[0-9]+)?$", s) is None:
        print("Doesn't look like a number")
        continue
    if '.' in s:
        print("Number will be truncated to integer.")
    temp = int(float(s))
    if not (-50 <= temp <= 5):
        print("Out of range")
        continue
    break

替换标点符号:

if temperature.replace('-','').replace('.','').isnumeric():