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

Python循环问题求助:猜数字游戏无法实现重玩循环功能

问题分析与修复

你的代码存在几个关键问题导致无法重新游玩和清屏:

  • 外层仅用if判断,没有循环逻辑,单次游戏结束后无法重启
  • 猜对提示print("you got the number")放在while循环内,每次输入都会打印,而非仅猜对时显示
  • os.system(clear)中clear未加引号,且未考虑Windows系统(Windows清屏命令是cls)
  • 模块导入放在if块内,重复导入不符合规范,且初始play变量类型与后续输入的字符串不匹配
修正后的代码
import os
import random
import time

def clear_screen():
    # 跨平台清屏,适配Windows/Linux/macOS
    os.system('cls' if os.name == 'nt' else 'clear')

play = "yes"
while play.lower() in ["yes", "y"]:
    clear_screen()
    n = random.randint(1, 10)
    g = 0
    time.sleep(0.25)
    print("guess the number 1-10")
    time.sleep(0.5)
    
    while g != n:
        g = int(input("what is your guess? "))
        if g < n:
            print("too low, guess again")
        elif g > n:
            print("too high, guess again")
        else:
            print("you got the number!")
    
    play = input("play again? (yes/no) ")

clear_screen()
关键修改说明
  • 模块统一放到顶部导入,避免重复导入
  • 新增clear_screen()函数实现跨平台清屏,解决不同系统的清屏命令差异
  • 外层用while循环控制游戏重启,只要输入yes或y就重新开始
  • 猜对提示移到else分支,仅当猜对时才显示
  • 每次进入游戏前先清屏,符合需求
  • 统一play变量为字符串类型,通过lower()兼容大小写输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:23:13