Python 整数输入指南:用 `get_integer()` 稳健读取用户输入

原创2026-10-14 22:25:511,850 阅读
文章标签:示例工程

Python 整数输入指南:用 get_integer() 稳健读取用户输入

导读

命令行交互程序的第一步,往往是从用户那里读取一个数字,而 Python 的 input() 返回的永远是一个字符串——直接拿去用,轻则类型错误,重则程序崩溃。本文围绕仓库 python-input-integer 中配套的 number_input.py 展开,系统讲解如何用 int() 完成字符串到整数的转换、如何用 ValueError 捕获非法输入,并给出 get_integer()、get_float()、get_integer_with_default() 三个可直接复制使用的稳健输入函数。读完本文,你将能写出无论用户输入什么都不会崩的数值读取代码。

为什么 input() 返回的是字符串

Python 内建函数 input(prompt) 会把用户敲下的所有字符原样作为一个字符串返回。即使你输入的是 42,得到的也是字符串 "42",而不是数字 42。因此,最常见的整数读取写法是:

number = int(input("Please enter a number: "))

int() 会把可解析的字符串转换为整数,例如 "42"、"+5"、"-3",甚至带首尾空格的 " 42 " 都能成功转换。但如果用户输入了 "abc"、"4.5" 或直接敲回车,int() 就会抛出 ValueError,程序立刻中断:

ValueError: invalid literal for int() with base 10: 'abc'

这正是所有数值输入程序必须面对的核心问题:你无法假设用户会输入什么,必须为非法输入兜底。

朴素的 try/except 写法及其缺陷

最简单的兜底做法是用 try/except 包裹转换逻辑,但很多初学者会写成一次性尝试,比如:

try:
    number = int(input("Please enter a number: "))
except ValueError:
    print("That's not a valid number!")

这种写法的问题在于:用户第二次输入仍然是非法内容时,程序没有再次提示和校验,交互体验是断裂的。真正稳健的做法是让输入校验形成一个循环,直到拿到合法整数为止——这正是 get_integer() 的设计思路。

核心函数 get_integer():循环校验直到合法

仓库中的 number_input.py 为教程提供了配套实现,其核心函数 get_integer() 源码如下(见 number_input.py):

def get_integer(prompt: str, error_message: str = None) -> int:
    """Prompts the user for an integer value.

    If the input is invalid, prints error_message (if specified) and then
    repeats the prompt.
    """
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            if error_message:
                print(error_message)

逐行拆解它的工作流程:

  1. while True: 无限循环——保证函数只有在拿到合法整数时才会返回,非法输入永远无法让函数退出,从结构上杜绝了"输入一次就放弃"的体验问题;
  2. return int(input(prompt))——input(prompt) 先展示提示语并读取字符串,紧接着 int() 尝试转换;转换成功则 return 同时退出循环,转换失败则抛出 ValueError;
  3. except ValueError:——只捕获转换失败这一类异常,程序不会中断,而是回到循环顶部重新提示;
  4. if error_message: 可选提示——如果调用者传入了 error_message,则在每次非法输入后打印该提示;不传则静默重试。注意这是一个"可选增强"设计:错误提示是加分项,而校验循环本身才是函数不崩溃的根基。

调用方式

from number_input import get_integer

age = get_integer("How old are you? ")
print(f"You are {age} years old.")

此时如果用户输入 abc,会得到一次"请重新输入"的机会(无提示则静默重试),直到输入 30 这样的合法整数,函数才返回 30 并继续执行后续代码。

带自定义错误消息

from number_input import get_integer

age = get_integer(
    "How old are you? ",
    error_message="Invalid integer!",
)

效果是:用户输入 abc 时,终端会打印 Invalid integer!,然后再次显示 How old are you? 提示。

扩展一:get_float() 读取浮点数

整数方案稍加改动即可迁移到浮点数。get_float() 与 get_integer() 完全同构,只是把 int() 换成 float()(见 number_input.py):

def get_float(prompt: str, error_message: str = None) -> float:
    """Prompts the user for a float value.

    If the input is invalid, prints error_message (if specified) and then
    repeats the prompt.
    """
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            if error_message:
                print(error_message)

float() 可以解析 "3.14"、"-0.5"、"1e3" 等常见浮点字面量,遇到 "abc" 或 "1,5"(注意逗号不会被识别为小数点)则抛出 ValueError。适合用于价格、比例、温度等需要小数的场景:

from number_input import get_float

price = get_float(
    "Enter the price: ",
    error_message="Invalid float!",
)

扩展二:get_integer_with_default() 支持默认值回退

交互式命令行工具中,"直接回车使用默认值"是常见需求。get_integer_with_default() 在整数校验的基础上增加了空输入回退逻辑(见 number_input.py):

def get_integer_with_default(
    prompt: str, default_value: int, error_message: str = None
) -> int:
    """Prompts the user for an integer, and falls back to a default value.

    If the input is an empty string, then the function returns default_value.
    Otherwise, if the input is not a valid integer, prints error_message (if
    specified) and then repeats the prompt.
    """
    while True:
        input_string = input(prompt)
        if not input_string:
            return default_value
        try:
            return int(input_string)
        except ValueError:
            if error_message:
                print(error_message)

与 get_integer() 相比有三个关键差异:

  1. 先读后转——先用 input_string = input(prompt) 拿到原始字符串,再决定如何处理;
  2. 空输入判断——if not input_string: 捕获用户直接回车的情况(空字符串是假值),此时直接返回 default_value,跳过转换;
  3. 转换逻辑不变——非空输入仍然走 int() 转换 + ValueError 捕获,非法输入会循环重试。

典型使用场景是"询问超时时间,默认 30 秒":

from number_input import get_integer_with_default

timeout = get_integer_with_default(
    "Enter timeout in seconds: ",
    default_value=30,
    error_message="That's not a valid integer!",
)

用户直接回车得到 30,输入 60 得到 60,输入 abc 则打印错误提示并重新询问。

作为脚本运行:内置的自测演示

number_input.py 的 __main__ 入口自带一段演示代码(见 number_input.py),把三个函数各调用一次并打印返回值:

if __name__ == "__main__":
    # Test functions when running as a script.
    print(get_integer("Test get_integer(): "))
    print(
        get_integer(
            "Test get_integer() with an error message: ",
            error_message="Invalid integer!",
        )
    )
    print(
        get_float(
            "Test get_float() with an error message: ",
            error_message="Invalid float!",
        )
    )
    print(
        get_integer_with_default(
            "Test get_integer_with_default(): ",
            default_value=99,
            error_message="That's not a valid integer!",
        )
    )

直接运行该文件即可逐个体验四种交互形态:

python number_input.py
  • 第一次输入:无错误提示的整数读取;
  • 第二次输入:带 Invalid integer! 提示的整数读取;
  • 第三次输入:带提示的浮点数读取;
  • 第四次输入:默认值为 99 的整数读取(直接回车返回 99)。

if __name__ == "__main__": 保证该文件被 import 时不会执行演示代码,只暴露 get_integer、get_float、get_integer_with_default 三个函数供其他模块复用。

三个函数的选型建议

函数 返回类型 空输入处理 适用场景
get_integer(prompt, error_message=None) int 继续循环询问 年龄、数量、序号等必须提供整数的场景
get_float(prompt, error_message=None) float 继续循环询问 价格、比例、测量值等小数场景
get_integer_with_default(prompt, default_value, error_message=None) int 返回 default_value 超时秒数、重试次数等有缺省值的配置项

从源码结构看,三者的共同设计模式是"无限循环 + try/except 转换 + 可选错误消息",区别只在于转换目标类型(int/float)和是否处理空输入。这套模式可以继续泛化:例如把 int() 换成 datetime.strptime() 就能得到日期读取函数,换成自定义解析器就能得到任意格式的校验输入函数——循环兜底的骨架是不变的。

小结与仓库指引

读取整数输入的关键结论可以浓缩为三点:

  1. input() 永远返回字符串,必须用 int()(或 float())显式转换;
  2. 转换可能抛出 ValueError,务必用 try/except 捕获,否则非法输入会直接终止程序;
  3. 把校验放进 while True 循环,让函数"拿不到合法值就不返回",再配合可选的错误提示和默认值回退,就能得到健壮的交互式输入体验。

本文讲解的完整可运行代码位于仓库 python-input-integer 目录下的 number_input.py,可直接导入使用,也可作为模板改造出符合自己业务需求的校验函数。

登录后查看全文
materials