Python demo 脚本学习 -beer.py

2021-10-14
标签: PYTHON

本文是学习 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 写在同一行。

如果您对本站内容有疑问或者寻求合作,欢迎 联系邮箱邮箱已到剪贴板

标签: PYTHON

欢迎转载本文,惟请保留 原文出处 ,且不得用于商业用途。
本站 是个人网站,若无特别说明,所刊文章均为原创,并采用 署名协议 CC-BY-NC 授权。