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

基于YouTube教程的猜数字项目:low和high值不随输入更新

问题解决:猜数字游戏中low和high无法更新的问题

你的代码核心错误在于调用字符串小写方法时遗漏了括号,导致输入判断逻辑完全失效,进而无法更新low和high的值。

错误原因

input(...)后使用.lower而不是.lower()时,feedback变量存储的是字符串的lower方法对象,而非用户输入的小写字符串。这使得后续feedback=='h'或feedback=='l'的判断永远不成立,high和low自然不会随输入调整。

修正后的代码

import random  # 原代码遗漏了random模块导入,需补充

def computer_guess(x):
    low = 1
    high = x
    feedback = ''
    while feedback != 'c':
        print(f'high:{high} low:{low} feedback:{feedback}')
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low
        # 关键修正:添加()调用lower方法,将输入转为小写
        feedback = input(f'Is {guess} too high(h), too low(l), or correct(c)? ').lower()
        if feedback == 'h':
            high = guess - 1
        elif feedback == 'l':
            low = guess + 1
    print(f'Yay, the computer guessed the number, {guess}, correctly!')

computer_guess(100)

额外说明

  1. 补充了import random语句,否则random.randint会抛出未定义错误
  2. 修正了输入提示中的拼写错误(to high改为too high)和输出文本的拼写错误(comptuer改为computer)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:02:34