python趣味小程序

以下是一个简单的Python趣味小程序,可以猜数字游戏:

import random

def guess_number():
    target_number = random.randint(1, 100)
    attempts = 0
    
    while True:
        guess = int(input("请输入一个1到100之间的整数:"))
        attempts += 1
        
        if guess < target_number:
            print("猜小了!")
        elif guess > target_number:
            print("猜大了!")
        else:
            print(f"恭喜你猜对了!答案是{target_number},你一共猜了{attempts}次。")
            break

guess_number()

运行程序后,它会随机生成一个1到100之间的整数作为目标数字,然后你需要输入一个猜测的数字。程序会根据你的猜测给出提示,直到你猜对为止。最后,程序会告诉你猜对了,并显示你猜的次数。

希望你喜欢这个小程序!

当然,还有很多其他有趣的Python小程序。以下是一些例子:

石头、剪刀、布游戏:

import random

def rock_paper_scissors():
    choices = ["石头", "剪刀", "布"]
    computer_choice = random.choice(choices)
    user_choice = input("请输入你的选择(石头、剪刀、布):")
    
    if user_choice not in choices:
        print("请输入有效的选择!")
        return
    
    print(f"电脑选择了:{computer_choice}")
    
    if user_choice == computer_choice:
        print("平局!")
    elif (user_choice == "石头" and computer_choice == "剪刀") or (user_choice == "剪刀" and computer_choice == "布") or (user_choice == "布" and computer_choice == "石头"):
        print("你赢了!")
    else:
        print("你输了!")

rock_paper_scissors()

猜词游戏:

import random

def guess_word():
    words = ["apple", "banana", "orange", "grape", "watermelon"]
    target_word = random.choice(words)
    attempts = 0
    
    while True:
        guess = input("请输入一个水果名称:")
        attempts += 1
        
        if guess.lower() == target_word:
            print(f"恭喜你猜对了!答案是{target_word},你一共猜了{attempts}次。")
            break
        else:
            print("猜错了!请继续猜。")

guess_word()

这些小程序只是一些简单的例子,你可以根据自己的兴趣和创造力来编写更多有趣的Python小程序。希望这些例子能给你一些启发!