2014年5月22日木曜日

開発環境

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)、Code Magnets(p.183)を解いてみる。

Code Magnets(p.183)

コード(BBEdit)

sample183.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))

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: ')
        saveTransaction(price[choice - 1], credit_card, items[choice - 1])

入出力結果(Terminal)

$ ./sample183.py 
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 2
Credit card number: 6218967257405618
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 1
Credit card number: 9334337468457785
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 5
$ cat transaction.txt 
62189672574056180000200           LATTE
93343374684577850000150           DONUT
$ ./sample183.py 
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 4
Credit card number: 1234567890123456
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 3
Credit card number: 6543210987654321
1. DONUT
2. LATTE
3. FILTER
4. MUFFIN
5. Quit
Choose an option: 5
$ cat transaction.txt 
62189672574056180000200           LATTE
93343374684577850000150           DONUT
12345678901234560000120          MUFFIN
65432109876543210000180          FILTER
$ 

0 コメント:

コメントを投稿