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

Python猜数字游戏如何编写名称不等于quit的while判断语句

猜数字程序修改方案

完整可运行代码

# Write the statements requested in Steps 1-6 below
# See the examples in the provided code
# Use structured programming and indent your code.
# Programmer Name: *****add your name here****

import random

# uses randrange instead of randint for better results in Python 3.7 
# randrange stops just before the upper range, use (1, 11) for 1-10

num = random.randrange(1, 11)

# Step 1: Ask the player to enter a name or quit to exit
print("Hi, please enter your name or type 'quit' to exit.")    
name = input().strip() # 新增:获取用户输入的名称
   
# Step 2: use a while statement to test when the name is not equal to quit
while name != 'quit': # 直接在while条件判断名称不等于quit,无需额外赋值变量
  # Step 3: input enter a number from 1 to 10 for the variable your_guess
  your_guess = int(input("请输入1到10之间的数字:"))
   
  # display the number guessed
  print("Your number is", your_guess)

  while num != your_guess:
    # Step 4: Write an if statement for your_guess is less than num
    if your_guess < num:
      print("Your guess is too low.")
      your_guess = int(input("Guess another number from 1 to 10: "))
    elif your_guess > num:
      print("Your guess is too high")
      your_guess = int(input("Guess another number from 1 to 10: "))
    else:
      break

  print("The correct number was", num)
  # Step 5 display text with your guess and You won, name
  print(f"You won! {name}, 你猜对的数字是{your_guess}")

  print("***************************************************************")
  # Step 6 ask the player to enter a name or quit to exit
  print("请输入你的名称,或输入'quit'退出游戏:")
  name = input().strip()
  num = random.randrange(1, 11)
print("Thank you for playing!") 

核心修改说明(重点解决步骤2的疑问)

  • 原代码缺少获取用户输入的逻辑,打印提示后要调用input()把用户输入的内容赋值给name变量,才能做后续判断
  • 步骤2的while语句直接用while name != 'quit'作为判断条件即可,不需要额外定义a变量,每次循环结束时(对应步骤6)重新获取用户输入的name,就能实现输入quit就退出游戏的效果
  • 原代码缩进不符合Python规范,同一层级的代码缩进要保持一致,if/while下的子代码要统一缩进4个空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:12:04