2016年9月26日月曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 8(Working with Files)、44(Product Search)を取り組んでみる。

44(Product Search)

コード(Emacs)

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

import os
import json


def find(items, name):
    for d in items:
        if d['name'] == name:
            return d
    return None

filename = 'products.json'
if not os.path.isfile(filename):
    products = dict(
        products=[
            dict(name='Widget', price=25.00, quantity=5),
            dict(name='Thing', price=15.00, quantity=5),
            dict(name='Doodad', price=5.00, quantity=10)
        ]
    )
    with open(filename, 'w') as f:
        json.dump(products, f)

with open(filename) as f:
    products1 = json.load(f)

product_list = products1['products']

while True:
    name = input('What is the product name? ')
    if name == 'q':
        break
    product = find(product_list, name)
    if product is None:
        print('Sorry, that product was not found in our inventory.')
        y = input('add? ')
        if y == 'y':
            price = input('Price: ')
            quantity = input('Quantity: ')
            product_list.append(
                dict(name=name, price=price, quantity=quantity))
    else:
        print('Name: {name}\nPrice: ${price}\nQuantity on hand: {quantity}'
              .format(**product))

with open(filename, 'w') as f:
    json.dump(products1, f)

入出力結果(Terminal, IPython)

$ ls products.json
ls: products.json: No such file or directory
$ ./sample44.py
What is the product name? iPad
Sorry, that product was not found in our inventory.
add? y
Price: 500.00
Quantity: 1
What is the product name? iPad
Name: iPad
Price: $500.00
Quantity on hand: 1
What is the product name? Widget
Name: Widget
Price: $25.0
Quantity on hand: 5
What is the product name? q
$ cat products.json 
{"products": [{"price": 25.0, "name": "Widget", "quantity": 5}, {"price": 15.0, "name": "Thing", "quantity": 5}, {"price": 5.0, "name": "Doodad", "quantity": 10}, {"price": "500.00", "name": "iPad", "quantity": "1"}]}$ 

0 コメント:

コメントを投稿