99 Bottles of Beer

在互联网上有一个叫 “99 Bottles of Beer” 的 Python 脚本,它是一个经典的调用自身的程序,它会打印出 99 次 “99 bottles of beer on the wall” 的歌词:

def sing_99_bottles():
    for i in range(99, 0, -1):
        print(f"{i} bottles of beer on the wall, {i} bottles of beer.")
        print(f"Take one down, pass it around, {i-1} bottles of beer on the wall.")
        print()

sing_99_bottles()

运行程序将会打印出 99 行歌词,每一行都是 “X bottles of beer on the wall, X bottles of beer. Take one down, pass it around, X-1 bottles of beer on the wall.”,X 是从 99 到 1 的整数。

如果你想调整啤酒瓶数量,只需要修改 range 里的值就好了。

实现一个跑字(Matrix-style)的小程序:

运行程序将会打印出一个长度为 80 个字符的随机字符串,每隔 50 毫秒打印一次,效果就像是跑字一样。

import random
import time

def matrix_effect():
    symbols = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
    while True:
        string = "".join([random.choice(symbols) for _ in range(80)])
        print(string)
        time.sleep(0.05)

matrix_effect()

一个简单的画板程序

from turtle import *

def draw_something():
    while True:
        forward(200)
        left(170)
        if abs(pos()) < 1:
            break

draw_something()

运行程序会开启一个小窗口, 画板会向前移动,并不断向左转,形成一个类似于螺旋的图形。

调用 API 显示图像

下述代码会使用 Unsplash 的 API 加载一个随机图片并显示在屏幕上。

对于最后一个代码需要用到 Unsplash 的 API,需要注册一个帐号并用 Access_key 替换上面代码中 YOUR_ACCESS_KEY 这个地方。

import requests
from PIL import Image

def show_a_picture():
    url = "https://api.unsplash/photos/random"
    params = {"client_id": YOUR_ACCESS_KEY}
    response = requests.get(url, params=params)
    data = response.json()
    img_url = data["urls"]["full"]
    img = Image.open(requests.get(img_url, stream=True).raw)
    img.show()

show_a_picture()

更多推荐

给你一个 Python 趣味代码的案例~