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

如何让Python猜数字游戏猜对后停止运行?

数字猜谜游戏:猜对后仍继续循环的问题解决方法

问题情况

刚学习Python不久,第一个项目是制作一个简易数字猜谜游戏。当前游戏在第一次或第二次猜对数字后,会提示"Good job!"但仍继续要求输入数字直到第三次尝试,希望修改代码解决该问题。

原代码如下:

import random

n = random.randint(1,10)

guess = None
count = 1
max_guesses = 3

while True:
    guess = input("Please type a number between 1-10:")


    if int(guess) < n: print ("Too low")

    elif int(guess) > n: print("Too high")


    else : print ("Good job!") 


    count += 1
    if count > max_guesses:
        print("You ran out of guesses! the number was " + str(n))
        break

尝试过调整代码位置和break语句的位置,但因学习时间短未能解决。

解决方法

问题核心是猜对数字后没有终止循环,当前代码只有在用完3次机会时才会执行break。只需在猜对的分支(else块)里添加break语句,就能在用户猜对后立即结束游戏。

修改后的代码:

import random

n = random.randint(1,10)

guess = None
count = 1
max_guesses = 3

while True:
    guess = input("Please type a number between 1-10:")

    if int(guess) < n: 
        print ("Too low")
    elif int(guess) > n: 
        print("Too high")
    else: 
        print ("Good job!")
        break  # 猜对后直接终止循环

    count += 1
    if count > max_guesses:
        print("You ran out of guesses! the number was " + str(n))
        break

额外小提示:把print语句单独换行排版,能让代码可读性更好,就像上面修改后的代码那样。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:22:15