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

课程作业:如何改写ask_int_between函数中的while True循环?

问题描述

课程作业要求编写ask_int_between(lo, hi)函数,需满足以下要求:

  • 提示用户输入整数
  • 验证输入是否为lo到hi范围内的有效整数,符合条件则返回该值
  • 输入不符合要求时输出对应提示
  • 必须使用给定的is_int(str)辅助函数

目前已实现基于while True循环的版本,但教授要求禁止使用while True循环,面对多条件检查的场景,不知道如何改写得简洁易读。

现有代码如下:

def ask_int_between(lo, hi):
    while True:
        result = input(f"Please enter a number from {lo} to {hi}:")
        if not is_int(result):
            print(f'''Please try again: I don't know what int "{result}" is.''')
        else:
            resultInt = int(result) # we now know this will work
            if resultInt < lo:
                print(f'''Please try again: {resultInt} is too low.''')
            elif resultInt > hi:
                print(f'''Please try again: {resultInt} is too high.''')
            else:
                return resultInt 
替代实现方案(无while True)

可以用递归调用替代循环,逻辑和原代码完全一致,同时满足教授的要求:

def ask_int_between(lo, hi):
    result = input(f"Please enter a number from {lo} to {hi}:")
    # 检查输入是否为有效整数
    if not is_int(result):
        print(f'''Please try again: I don't know what int "{result}" is.''')
        return ask_int_between(lo, hi)
    # 转换为整数后检查范围
    resultInt = int(result)
    if resultInt < lo:
        print(f'''Please try again: {resultInt} is too low.''')
        return ask_int_between(lo, hi)
    elif resultInt > hi:
        print(f'''Please try again: {resultInt} is too high.''')
        return ask_int_between(lo, hi)
    # 所有检查通过,返回有效整数
    return resultInt

实现思路

  • 函数每次执行时先获取用户输入,按顺序完成有效性、范围检查
  • 任何一项检查失败时,打印提示后递归调用自身,重新发起输入流程
  • 所有检查通过时直接返回结果,终止递归

这种写法结构清晰,和原代码的逻辑一一对应,完全规避了while True循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:25:37