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

Python猜数字程序运行异常:random.randint相关问题排查

问题分析与修复

你的程序闪退是因为存在两个关键错误,导致Python解释器无法正常执行代码,直接终止运行:

错误1:多行字符串未正确闭合

第一行print语句中的字符串跨了多行,但仅用一对双引号包裹,这会触发语法错误。Python中多行字符串需要用三引号("""或''')包裹,或者用换行符\n拼接。

错误2:整数与字符串直接拼接

print("Is it " + comGuess + "?")这一行中,comGuess是random.randint()返回的整数类型,不能直接和字符串用+拼接,必须先转换为字符串类型,用str(comGuess)。

修正后的完整代码

import random
print("""Think of a number between 0 - 100
Type:
'Higher' if the number is too low
'Lower' if the number is too high
'Correct' if the number is correct""")
minRange = 0
maxRange = 100
while True: 
    comGuess = random.randint(minRange, maxRange)
    print("Is it " + str(comGuess) + "?")   
    answer = input("")
    if answer in ("Higher", "higher", "h"):
        minRange = comGuess
    elif answer in ("Lower", "lower", "l"):
        maxRange = comGuess
    elif answer in ("Correct", "correct", "c"):
        input("Yay I won!")
        break
    else:
        print("I don't understand")

另外,建议在命令行中运行Python程序(比如python your_script.py),这样即使程序出错,也能看到具体的错误提示,方便排查问题,避免双击脚本文件导致窗口闪退看不到信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:45:35