2014年5月23日金曜日

開発環境

Head First Programming A learner's guide to programming using the Python language (David Griffiths(著)、Paul Barry(著)、 O'Reilly Media; )のChapter 6(Modular Programming: Keeping things straight)、Sharpen your pencil(p.195)を解いてみる。

Sharpen your pencil(p.195)

コード(BBEdit)

transactions.py

#!/usr/bin/env python3
#-*- coding: utf-8

def saveTransaction(price, credit_card, description):
    with open('transaction.txt', 'a') as f:
        f.write('{0:16s}{1:07d}{2:>16s}\n'.format(
            credit_card, int(price * 100), description))

gym_pos.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import transactions

items = ['DONUT', 'LATTE', 'FILTER', 'MUFFIN']
price = [1.50, 2.0, 1.80, 1.20]
running = True

while running:
    option = 1
    for choice in items:
        print('{0}. {1}'.format(str(option), choice))
        option = option + 1
    print('{0}. Quit'.format(str(option)))
    choice = int(input('Choose an option: '))
    if choice == option:
        running = False
    else:
        credit_card = input('Credit card number: ')
        transactions.saveTransaction(
            price[choice - 1], credit_card, items[choice - 1])

coffee_pos.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import transactions

items = ['WORKOUT', 'WEIGHTS', 'BIKES']
price = [35.0, 10.0, 8.0]
running = True

while running:
    option = 1
    for choice in items:
        print('{0}. {1}'.format(str(option), choice))
        option = option + 1
    print('{0}. Quit'.format(str(option)))
    choice = int(input('Choose an option: '))
    if choice == option:
        running = False
    else:
        credit_card = input('Credit card number: ')
        transactions.saveTransaction(
            price[choice - 1], credit_card, items[choice - 1])

入出力結果(Terminal)

$ ./gym_pos.py 
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 1
Credit card number: 1234567890123456
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 5
$ cat transaction.txt 
12345678901234560000150           DONUT
$ ./coffee_pos.py 
1. WORKOUT
2. WEIGHTS
3. BIKES
4. Quit
Choose an option: 2
Credit card number: 6543210987654321
1. WORKOUT
2. WEIGHTS
3. BIKES
4. Quit
Choose an option: 4
$ cat transaction.txt 
12345678901234560000150           DONUT
65432109876543210001000         WEIGHTS
$ 

0 コメント:

コメントを投稿