Skip to content

Commit 0396cfb

Browse files
committed
chapter 11
1 parent 0f5477a commit 0396cfb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

11_bottles_of_beer/bottles.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#! /usr/bin/env python3
2+
3+
import argparse
4+
5+
def get_args():
6+
parser = argparse.ArgumentParser(
7+
prog='bottles.py',
8+
description='Bottles of beer song')
9+
10+
parser.add_argument('-n', '--num',
11+
metavar='number',
12+
help='How many bottles (default: 10)',
13+
default=10,
14+
type=int)
15+
16+
args = parser.parse_args()
17+
18+
if args.num < 1:
19+
parser.error(f'--num "{args.num}" must be greater than 0')
20+
21+
return args
22+
23+
def verse(bottles):
24+
25+
next_bottle = bottles -1 if bottles > 1 else 0
26+
27+
s1 = '' if bottles == 1 else 's'
28+
s2 = 'No more' if bottles == 1 else f'{next_bottle}'
29+
s3 = '' if next_bottle == 1 else 's'
30+
s4 = '\n' if next_bottle > 0 else ''
31+
32+
return '\n'.join([
33+
f'{bottles} bottle{s1} of beer on the wall,',
34+
f'{bottles} bottle{s1} of beer,',
35+
'Take one down, pass it around,',
36+
f'{s2} bottle{s3} of beer on the wall!{s4}'])
37+
38+
def test_verse():
39+
"""Test verse"""
40+
41+
last_verse = verse(1)
42+
assert last_verse == '\n'.join([
43+
'1 bottle of beer on the wall,',
44+
'1 bottle of beer,',
45+
'Take one down, pass it around,',
46+
'No more bottles of beer on the wall!'])
47+
48+
49+
last_verse = verse(2)
50+
assert last_verse == '\n'.join([
51+
'2 bottles of beer on the wall,',
52+
'2 bottles of beer,',
53+
'Take one down, pass it around,',
54+
'1 bottle of beer on the wall!'])
55+
56+
def main():
57+
58+
args = get_args()
59+
60+
print('\n'.join(map(verse, range(args.num, 0, -1))))
61+
62+
if __name__ == '__main__':
63+
main()

0 commit comments

Comments
 (0)