python猜數(shù)游戲代碼怎么寫(xiě)

小億
168
2023-12-21 09:01:21

以下是一個(gè)簡(jiǎn)單的Python猜數(shù)游戲的代碼示例:

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()

這個(gè)程序會(huì)隨機(jī)生成一個(gè)1到100之間的整數(shù),然后提示用戶(hù)猜這個(gè)數(shù)是多少。用戶(hù)每猜一次,程序會(huì)給出相應(yīng)的提示,直到用戶(hù)猜中為止。程序會(huì)記錄用戶(hù)猜的次數(shù),并在用戶(hù)猜中后顯示出來(lái)。用戶(hù)可以通過(guò)輸入數(shù)字猜測(cè),程序會(huì)根據(jù)用戶(hù)的輸入給出相應(yīng)的提示(猜的數(shù)字太高或太低)。當(dāng)用戶(hù)猜中時(shí),程序會(huì)顯示祝賀消息并結(jié)束游戲。

注意:這只是一個(gè)簡(jiǎn)單的猜數(shù)游戲示例,你可以根據(jù)自己的需求進(jìn)行修改和擴(kuò)展。

0