4

Python demo 脚本学习 -beer.py

 2 years ago
source link: https://www.lfhacks.com/tech/python-demo-beer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

本文是学习 Python 自带脚本第一篇:beer.py,来自一首歌谣。

啤酒瓶歌谣

经典的啤酒瓶歌谣, 99 bottles of beer on the wall ,用简单的几句来体现编程语言的的特点。

其他语言的样例在 这里

其中 Python 版本是 Fredrik Lundh 写的,但是有些不好读懂。经 Python 的创始人 Guido van Rossum 简化后的版本提供在 Python 安装包里。如下节所示:

#!/usr/bin/env python3

"""
A Python version of the classic "bottles of beer on the wall" programming
example.

By Guido van Rossum, demystified after a version by Fredrik Lundh.
"""

import sys

n = 100
if sys.argv[1:]:
    n = int(sys.argv[1])

def bottle(n):
    if n == 0: return "no more bottles of beer"
    if n == 1: return "one bottle of beer"
    return str(n) + " bottles of beer"

for i in range(n, 0, -1):
    print(bottle(i), "on the wall,")
    print(bottle(i) + ".")
    print("Take one down, pass it around,")
    print(bottle(i-1), "on the wall.")

传递参数 3 后,执行的效果如下:

$ python beer.py 3
3 bottles of beer on the wall,
3 bottles of beer.
Take one down, pass it around,
2 bottles of beer on the wall.
2 bottles of beer on the wall,
2 bottles of beer.
Take one down, pass it around,
one bottle of beer on the wall.
one bottle of beer on the wall,
one bottle of beer.
Take one down, pass it around,
no more bottles of beer on the wall.

按照给定的参数,生成了一套歌词。

仔细观察,每段有4句歌词,对于大于1的情况下,4句歌词是这样的结构:

n bottles of beer on the wall,
n bottles of beer.
Take one down, pass it around,
n-1 bottles of beer on the wall.

所以程序开启一段循环,在循环体内打印出这四句歌词。而对于歌词里重复的部分(n bottles of beer),则可以抽象出一个函数来复用。

下面逐行分析特点

docstring

脚本开始的多行字符串,是文档的 docstring,可以当作帮助文档使用。如果新开一个脚本如下所示,就能访问到。

import beer

print(beer.__doc__)

可以在命令行上看到这两句话


A Python version of the classic "bottles of beer on the wall" programming
example.

By Guido van Rossum, demystified after a version by Fredrik Lundh.

判断参数个数

if sys.argv[1:]:

判断脚本是否传入了参数,一般我们用 len(sys.argv) ,这里可能是作者希望表现出 Python 的 slicing 功能。

for i in range(n, 0, -1):

range(m,n,i) 的作用是以m为闭区间起点,n为开区间终点,i为步长的等差数列。

def bottle(n):

函数名后面的冒号容易忽略。

if n == 0: return "no more bottles of beer"
if n == 1: return "one bottle of beer"
return str(n) + " bottles of beer"

因为 return 即结束执行函数,所以这里不需用 else 来表示条件分支。

if 条件下的执行体,如果比较短小,可以和 if 写在同一行。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK