beer.py Well-known programming example: Bottles of beer.
beer.py Well-known programming example: Bottles of beer.
Github:https://github.com/python/cpython/blob/master/Tools/demo/beer.py
#!/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.")
在 jupyter lab 中运行报错:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-18-d31cdec36abd> in <module>
11 n = 100
12 if sys.argv[1:]:
---> 13 n = int(sys.argv[1])
14
15 def bottle(n):
ValueError: invalid literal for int() with base 10: '-f'
【解决办法】
查找 sys.argv[] 的用法:
https://docs.python.org/zh-cn/3/library/sys.html?highlight=argv#sys.argv
sys.argv
The list of command line arguments passed to a Python script.
argv[0] is the script name (it is operating system dependent whether
this is a full pathname or not). If the command was executed using the
-c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter,
argv[0] is the empty string.To loop over the standard input, or the list of files given on the
command line, see the fileinput module.
sys.argv[] 是传递给 Pythen 脚本文件的命令行参数列表。
把 beer.py 下载到本地,
chmod 777 beer.py
$./beer.py
100 bottles of beer on the wall,
100 bottles of beer.
Take one down, pass it around,
99 bottles of beer on the wall.
99 bottles of beer on the wall,
99 bottles of beer.
Take one down, pass it around,
98 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.
如果执行:
$./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.
自此明白, sys.argv[1]的作用是获取 Python 脚本运行时给定的命令行参数。同样,如果运行:
$./beer.py 3 4
则
sys.argv[1] = 3
sys.argv[2] = 4
至于 sys.argv[0],默认获取的是 Python 脚本文件名。
【收获】
学会了 sys.argv[] 的用法;
不是所有的命令都可以用 jupyter lab 来测试;况且 beer.py 文件开头也注明了#!/usr/bin/env python3
多查官方文档。Python 的文档写的很不错,而且最近也推出了中文的版本。