@@ -1470,6 +1470,66 @@ There's a slightly easier way to get that list by using the `reversed` function:
14701470
14711471
14721472
1473+ \newpage
1474+
1475+ # # Solution
1476+
1477+ ` ` ` `
1478+ 1 # !/usr/bin/env python3
1479+ 2 """Bottle of beer song"""
1480+ 3
1481+ 4 import argparse
1482+ 5
1483+ 6
1484+ 7 # --------------------------------------------------
1485+ 8 def get_args() :
1486+ 9 """get command-line arguments"""
1487+ 10
1488+ 11 parser = argparse.ArgumentParser(
1489+ 12 description='Bottles of beer song',
1490+ 13 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
1491+ 14
1492+ 15 parser.add_argument('-n',
1493+ 16 '--num',
1494+ 17 metavar='INT',
1495+ 18 type=int,
1496+ 19 default=10,
1497+ 20 help='How many bottles')
1498+ 21
1499+ 22 args = parser.parse_args()
1500+ 23
1501+ 24 if args.num < 1 :
1502+ 25 parser.error('--num ({}) must > 0'.format(args.num))
1503+ 26
1504+ 27 return args
1505+ 28
1506+ 29
1507+ 30 # --------------------------------------------------
1508+ 31 def main() :
1509+ 32 """Make a jazz noise here"""
1510+ 33
1511+ 34 args = get_args()
1512+ 35 tmpl = '\n'.join([
1513+ 36 '{} bottle{} of beer on the wall,',
1514+ 37 '{} bottle{} of beer,',
1515+ 38 'Take one down, pass it around,',
1516+ 39 '{} bottle{} of beer on the wall!',
1517+ 40 ])
1518+ 41
1519+ 42 for bottle in reversed(range(1, args.num + 1)) :
1520+ 43 next_bottle = bottle - 1
1521+ 44 s1 = '' if bottle == 1 else 's'
1522+ 45 s2 = '' if next_bottle == 1 else 's'
1523+ 46 print(tmpl.format(bottle, s1, bottle, s1, next_bottle, s2))
1524+ 47 if bottle > 1 :
1525+ 48 print()
1526+ 49
1527+ 50
1528+ 51 # --------------------------------------------------
1529+ 52 if __name__ == '__main__' :
1530+ 53 main()
1531+ ` ` ` `
1532+
14731533\newpage
14741534
14751535# # Discussion
0 commit comments