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

猜数字游戏程序优化需求:实现祝贺后循环直至输入0退出

修改后的猜数字游戏代码

以下是调整逻辑后的代码,实现猜对数字后自动开启新一局,直到输入0退出:

import random
import datetime

e = datetime.datetime.now()
print(e.strftime("%B %d,%Y @ %H:%M:%S"))

name = input("\nEnter your name: ")
 
def main():
    while True:
        # 每局生成新的随机数
        number = random.randint(1, 100)
        print(f"\nHi, {name}, Welcome to the Guessing Number Game ")
        x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
        if x == 0:
            print("You quit? Goodbye!")
            break
        # 调用猜数字函数,若中途退出则终止循环
        if not playGuessingGame(x, number):
            break

def playGuessingGame(x, number):
    times = 1
    while number != x:
        if x == 0:
            print("You quit? Goodbye!")
            return False
        times += 1
        if x < number:
            print("Too low, try again")
            x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
        elif x > number:
            print("Too high, try again")
            x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
    
    print(f"Congratulations {name}!, you guessed the right number with {times} tries!")
    # 猜对后返回True,触发新一局
    return True

main()

关键调整说明

  • 全局随机数改局内生成:把number = random.randint(1,100)移到main的循环里,保证每局都是不同的随机数
  • 循环式游戏流程:main函数用while True包裹,猜对后自动进入下一局,输入0则执行break退出
  • 中途退出处理:在playGuessingGame中增加对输入0的判断,中途输入0时返回False,让main循环终止
  • 函数参数传递:把每局的随机数number作为参数传给playGuessingGame,避免全局变量耦合
  • 移除测试打印:删掉了原代码中用于测试的print(number)语句,正常游戏不会泄露答案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:05:27