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("輸入你的猜測: "))`。

相關主題