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

为何第一段Python代码存在布尔错误,第二段却正常运行?

两段Python输入校验代码的错误分析

第一段代码运行时会触发布尔类型错误,第二段调整写法后可正常运行,具体原因如下:

第一段错误代码

def check_input():
    choice = 'wrong'
    digit = False
    
    while choice.isdigit() == False or digit == False:
        
        choice = input('Enter the value: ')
        
        if choice.isdigit() == False:
            print('Please enter the digit between 0 to 10')
            
        if choice.isdigit() == True:
            if int(choice) < 1 and int(choice) > 10:
                digit = False
            else:
                choice = True
                       
    return int(choice)

第二段正确代码

def check_input():
    choice = 'wrong'
    within_range = False
    acceptable_range = range(0,10)
    
    while choice.isdigit() == False or within_range == False:
        
        choice = input('Enter the value: ')
        
        if choice.isdigit() == False:
            print('Please enter the digit between 0 to 10')
            
        if choice.isdigit() == True:
            if int(choice) in acceptable_range:
                within_range = True
            else:
                within_range = False
 
    return int(choice)

错误原因分析

第一段代码的两个致命问题:

  1. 范围判断逻辑完全错误:
    代码里写的int(choice) < 1 and int(choice) > 10,一个数字不可能同时小于1且大于10,这个条件永远不会成立,意味着digit变量永远不会被设为True,循环无法正常退出。
  2. 非法修改变量类型:
    当输入合法数字时,代码执行choice = True,把原本是字符串类型的choice改成了布尔值True。下一次循环执行choice.isdigit()时,布尔类型没有isdigit()方法,直接触发AttributeError(也就是你看到的布尔错误)。

第二段代码的修正点:

  1. 范围判断逻辑正确:
    用range(0,10)定义合法范围,通过int(choice) in acceptable_range判断数字是否在范围内,逻辑清晰且正确。
  2. 保持变量类型一致:
    用单独的within_range变量标记是否符合范围要求,全程没有修改choice的类型,choice始终是用户输入的字符串,循环中每次调用choice.isdigit()都能正常执行,不会触发类型错误。

内容的提问来源于stack exchange,提问作者Mohammed Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:27:26