用于提示用户输入号码的功能

def input_number(msg, err_msg=None):
    while True:
        try:
            return float(raw_input(msg))
        except ValueError:
            if err_msg is not None:
                print(err_msg)

def input_number(msg, err_msg=None):
    while True:
        try:
            return float(input(msg))
        except ValueError:
            if err_msg is not None:
                print(err_msg)

并使用它:

user_number = input_number("input a number: ", "that's not a number!")

或者,如果你不想要错误消息

user_number = input_number("input a number: ")