以下是一個簡單的Python猜數游戲的代碼示例:
import random
def guess_number_game():
number_to_guess = random.randint(1, 100)
num_guesses = 0
print("Welcome to the Guess the Number Game!")
print("I'm thinking of a number between 1 and 100. Can you guess it?")
while True:
guess = int(input("Enter your guess: "))
num_guesses += 1
if guess < number_to_guess:
print("Too low. Try again!")
elif guess > number_to_guess:
print("Too high. Try again!")
else:
print(f"Congratulations! You guessed the number in {num_guesses} tries.")
break
guess_number_game()
這個程序會隨機生成一個1到100之間的整數,然后提示用戶猜這個數是多少。用戶每猜一次,程序會給出相應的提示,直到用戶猜中為止。程序會記錄用戶猜的次數,并在用戶猜中后顯示出來。用戶可以通過輸入數字猜測,程序會根據用戶的輸入給出相應的提示(猜的數字太高或太低)。當用戶猜中時,程序會顯示祝賀消息并結束游戲。
注意:這只是一個簡單的猜數游戲示例,你可以根據自己的需求進行修改和擴展。