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

Python输入超出范围未触发循环重询,返回值与合法输入一致怎么解决?

问题原因
  • input()函数的返回值默认是字符串类型,而代码中判断的是answer是否属于整数范围range(0,9),不同类型的值判断相等时永远返回假,因此不管输入的内容是否符合数值范围要求,条件判断的结果都会偏离预期,无法触发循环重复提问。
解决方法

需要先将用户输入的内容转换为整数类型后再做范围判断,同时新增异常处理逻辑避免用户输入非数字内容时程序崩溃,修正后的代码如下:

def ask_board_number(question):
    '''Asks enter the number from range'''
    answer = None
    while answer not in range(0, 9):
        try:
            # 将输入的字符串转换为整数
            answer = int(input(question))
        except ValueError:
            print("请输入0-8之间的有效数字")
    print('Your "X" is put in square number', answer)  
    return answer 

ask_board_number("\nInput the number of square, in that you want to put your 'X'. (0 - 8): ")

修改说明

  • 新增int()对输入结果做类型转换,统一为整数类型后再判断是否在目标范围内
  • 新增try-except捕获值错误异常,处理用户输入非数字的异常场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:15:04