1.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=100 n = int(sys.argv[1]) # sys.argv[]用来存放外部输入的数据,sys.argv[0]表示代码名字(包含路径),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.")
其中sys.argv的Python官方解释
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.
sys.argv[]用来存放外部输入的数据,sys.argv[0]表示代码名字(包含路径),sys.argv[1:]表示外部传入数据
比如你可以在命令行运行python beer.py 10,既可以使n=10
持续更新......