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

Python编写print_shampoo_instructions函数无限循环错误排查

错误原因排查
  • 缩进逻辑错误:while循环和增量语句i = i + 1的缩进位置完全错误:
    1. i = 0仅在else分支内定义,当num_cycles走<1或者>4的分支时,i变量未定义会直接报错
    2. i = i + 1没有放在while循环体内,导致循环中i的值永远是0,永远满足i < num_cycles的条件,触发无限循环,就是你遇到的Program end never reached报错
  • 函数名不匹配:你定义的函数名为shampoo_instructions,但程序要求调用的函数名是print_shampoo_instructions,调用时会找不到函数报错
  • 输出内容不符合要求:打印的Lather and rinse末尾缺少要求的.,最终打印的Done末尾也缺少要求的.
正确实现代码
def print_shampoo_instructions(num_cycles):
    if num_cycles < 1:
        print('Too few.')
    elif num_cycles > 4:
        print('Too many.')
    else:
        i = 0
        while i < num_cycles:
            print(f"{i+1} : Lather and rinse.")
            i += 1
        print('Done.')

user_cycles = int(input()) #cannot be altered per the program
print_shampoo_instructions(user_cycles) #cannot be altered per the program

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

相关产品推荐
方舟 Agent Plan

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

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