python60行完整代码实现的小功能

以下代码实现了一个简单的猜数字游戏代码。程序会在1到100之间生成一个随机数,然后让玩家猜这个数字,玩家最多有7次机会。程序会根据玩家的猜测告诉玩家猜的数字是偏高还是偏低,并在玩家猜对或次数用完后结束游戏。

以下是一个Python实现的小功能,代码共60行:

import random

def play_guessing_game():
    print("Welcome to the Guessing Game!")
    print("I'm thinking of a number between 1 and 100.")
    print("You have 7 guesses to find the correct number.")

    answer = random.randint(1, 100)
    guesses_left = 7
    guess = None

    while guess != answer and guesses_left > 0:
        print(f"You have {guesses_left} guesses left.")
        guess = int(input("What's your guess? "))
        if guess < answer:
            print("Too low! Try again.")
        elif guess > answer:
            print("Too high! Try again.")
        else:
            print(f"Congratulations! You guessed the number {answer}!")
        guesses_left -= 1

    if guess != answer:
        print(f"Sorry, you didn't guess the number {answer}. Better luck next time!")

if __name__ == '__main__':
    play_guessing_game()

该代码使用random库生成随机数,使用循环结构来处理玩家的猜测和游戏结束的逻辑,使用条件语句来根据猜测结果输出相应信息。在主程序中调用play_guessing_game函数启动游戏。

 
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定