Python是一种功能强大的编程语言,可以用于创建各种有趣和实用的程序。以下是一些有趣的Python代码示例:
猜数字游戏
import randomdef guess_the_number():number = random.randint(1, 100)attempts = 0while True:guess = int(input("请输入你的猜测:"))attempts += 1if guess < number:print("太小了,再试一次!")elif guess > number:print("太大了,再试一次!")else:print(f"恭喜你,猜对了!你一共用了{attempts}次机会。")break
石头剪刀布游戏
import randomdef rock_paper_scissors():choices = ["石头", "剪刀", "布"]computer_choice = random.choice(choices)user_choice = input("请输入你的选择(石头、剪刀、布):")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("你输了!")
密码生成器
import randomimport stringdef generate_password(length):return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(length))print(generate_password(10))

时光机
import timeimport datetimedef time_machine():print("输入指定日期即可穿越(只能到未来)")year = int(input("请输入目标年月日:"))month = int(input("请输入目标月份:"))day = int(input("请输入目标日期:"))target_date = datetime.datetime(year, month, day)while True:current_time = datetime.datetime.now()if current_time > target_date:print("时间旅行成功!当前时间是:", current_time)breaktime.sleep(1)
使用turtle绘制彩色螺旋
import turtlecolors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']turtle.bgcolor('black')turtle.speed('fastest')for x in range(360):turtle.pencolor(colors[x % len(colors)])turtle.width(x / 100 + 1)turtle.forward(x)turtle.left(59)turtle.done()
无限循环的进度条
import timedef progress_bar():while True:for progress in range(100):print('█', end='')time.sleep(0.1)print('\r进度:100%')
这些代码示例展示了Python在不同领域的应用,包括游戏、密码学、图形绘制等。你可以根据自己的兴趣和需求,尝试修改和扩展这些代码。
