You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制用户输入整数的位数?解决'int'对象无len()报错

解决object of type 'int' has no len()报错及限制整数输入位数的方法

报错原因与修复

你遇到的报错是因为把输入直接转成了整数(int)类型,而整数类型没有len()方法——len()仅能用于字符串、列表等可迭代对象。要修复这个问题,你需要先保留输入的字符串格式做长度校验,确认合法后再转成整数。

修正后的代码示例(加入循环让用户重新输入直到合法):

while True:
    student_id_str = input("Enter Student ID (8-digit number): ")
    # 先检查是否是纯数字且长度为8
    if student_id_str.isdigit() and len(student_id_str) == 8:
        student_id = int(student_id_str)
        print(f"Valid student ID: {student_id}")
        break
    else:
        print("Invalid input! Please enter an 8-digit number.")

限制用户输入整数位数的两种方法

1. 字符串层面校验(推荐)

直接对用户输入的字符串做检查:

  • 用isdigit()验证输入是否全为数字(避免字母、符号等非法输入)
  • 用len()检查字符串长度是否符合要求
  • 校验通过后再转换为整数,既保证格式正确,也能捕获非数字输入的情况

2. 数值范围校验

如果已经将输入转为整数,可以通过数值范围判断位数:
比如8位整数的范围是10000000 <= num <= 99999999,代码示例:

while True:
    try:
        student_id = int(input("Enter Student ID (8-digit number): "))
        if 10000000 <= student_id <= 99999999:
            print(f"Valid student ID: {student_id}")
            break
        else:
            print("Invalid! Please enter an 8-digit number.")
    except ValueError:
        print("Invalid input! Please enter only numbers.")

这种方法需要用try-except捕获用户输入非数字时的ValueError,否则会直接报错。

内容的提问来源于stack exchange,提问作者longoso mongy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:07:07