Skip to content

数字 Guessing Game

入门 约 15 分钟

你将构建什么

Python script 那个选取 random 数字之间 1 and 100, 读取 guesses in 循环, prints "Higher!" or "Lower!" 之后每个错误 guess, and congratulates player 当它们 win.

学习目标

  • Generate random integer 使用 random.randint
  • 读取用户输入使用输入() and convert 它到 int
  • Use 虽然循环那个 repeats 直到 guess 是正确
  • Track 数字的 attempts and print 它 at 端

前置要求

  • 变量 and assignment
  • 如果/else 语句
  • 虽然循环

步骤

  1. 1

    导入 random and 选取目标

    导入 random 模块 and 选取 secret 数字使用 random.randint(1, 100). Print welcome 消息所以 player knows 范围.

    代码
    import random
    
    target = random.randint(1, 100)
    print("I picked a number between 1 and 100.")

    预期结果

    运行 script prints welcome 消息; 目标持有隐藏数字.

  2. 2

    读取首先 guess

    Use 输入() 到读取 guess and int() 到 convert 它到 数字. 读取输入是 什么 lets 循环制作 progress.

    代码
    guess = int(input("Enter your guess: "))

    预期结果

    script waits for player 到类型数字 and 存储它 in guess.

  3. 3

    循环直到正确使用 hints

    Wrap comparison in 虽然 guess != 目标循环. 内部, print "Higher!" 如果 guess 是也 低, "Lower!" 如果也 高, 然后读取新 guess. 循环 exits 当 guess matches.

    代码
    while guess != target:
        if guess < target:
            print("Higher!")
        else:
            print("Lower!")
        guess = int(input("Enter your guess: "))
    print("You got it!")

    预期结果

    错误 guesses print 提示 and ask 再次; 正确 guess prints win 消息.

  4. 4

    数量 attempts

    添加 attempts 计数器那个开始 at 1 and increments 内部循环. Print 它 at 端所以 player sees 它们的 score.

    代码
    attempts = 1
    while guess != target:
        if guess < target:
            print("Higher!")
        else:
            print("Lower!")
        guess = int(input("Enter your guess: "))
        attempts += 1
    print(f"You got it in {attempts} tries!")

    预期结果

    之后 winning, script shows 如何许多 guesses player used.

  5. 5

    添加输入验证与异常处理

    在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。

    代码
    def safe_input(prompt, validator=None):
        """Read input with validation and error handling."""
        while True:
            try:
                raw = input(prompt)
                value = float(raw)
                if validator and not validator(value):
                    raise ValueError(f"Value {value} failed validation")
                return value
            except ValueError as err:
                print(f"Invalid input: {err}. Please try again.")
    
    # Usage
    age = safe_input("Enter your age: ", lambda x: x > 0)

    预期结果

    非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。

自己动手试试

你学到了什么

你组合 random.randint, 虽然循环, conditional 分支, and 输入读取到 完整 interactive game — 相同 control-flow shape used 通过许多 CLI programs.

相关资源

相关课程

  • 循环

    虽然循环那个 drives guessing 循环.

  • 条件

    如果/else 分支那个 compare guess 到目标.

相关练习

相关工具

相关速查表

相关参考文档

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题