Python猜数游戏

一个经典的 Python 初学者项目。构建一个使用随机生成、while 循环和用户输入验证的交互式猜数游戏。

在编辑器中尝试

概述

游戏是学习编程逻辑和流程控制的绝佳方式。

该脚本生成一个 1 到 100 之间的随机数,然后将用户困在“while”循环中,直到他们猜出正确的数字。

它通过检查他们对目标的猜测状态来提供提示(太高、太低)。

代码和执行输出

利用标准内置库的交互式猜数循环。

guessing_game.py
在编辑器中尝试
import random

def play_game():
    target = random.randint(1, 100)
    attempts = 0
    print("Welcome to the Number Guessing Game!")
    print("I'm thinking of a number between 1 and 100.")
    
    # Simulating a session (since input() blocks in standard runs, we mock it for the demo)
    mock_guesses = [50, 75, 60, 65, target]
    
    for guess in mock_guesses:
        attempts += 1
        print(f"\nYour guess: {guess}")
        
        if guess < target:
            print("Too low!")
        elif guess > target:
            print("Too high!")
        else:
            print(f"Congratulations! You guessed it in {attempts} attempts!")
            break

play_game()
端子输出
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.

Your guess: 50
Too low!

Your guess: 75
Too high!

Your guess: 60
Too low!

Your guess: ... (game continues)

逐步实施

  • 了解 while 循环的状态跟踪
  • 安全处理交互式 I/O 流
  • 逻辑门的实现

常见问题解答

如何使用实际的用户输入?

将模拟数组循环替换为 `while True:` 循环内的 `guess = int(input("输入你的猜测: "))`。

相关主题