2014年5月8日木曜日

開発環境

Head First Programming A learner's guide to programming using the Python language (David Griffiths(著)、Paul Barry(著)、 O'Reilly Media; )のChapter 3(functions: Let's get organized)、Sharpen your pencil(p.89)を解いてみる。

Sharpen your pencil(p.89)

コード(BBEdit)

sample89,.py

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

import urllib.request
import time

def getPrice():
    page = urllib.request.urlopen(
        'http://www.beans-r-us.appspot.com/prices.html')
    text = page.read().decode('utf8')
    where = text.find('>$')
    start_of_price = where + 2
    end_of_price = start_of_price + 4
    return text[start_of_price:end_of_price]


question = input('Is price required immediately?(Y/N): ')

if question == 'Y':
    price = getPrice()
else:
    price = 99.99
    # s = 60 * 15
    s = 5
    while price > 4.74:
        time.sleep(s)
        price = float(getPrice())
        # テスト用
        print(time.gmtime().tm_sec)
        print('price: {0}'.format(price))
        
print(price)
print('Buy!')

入出力結果(Terminal)

$ ./sample89.py
Is price required immediately?(Y/N): Y
5.88
Buy!
$ ./sample89.py
Is price required immediately?(Y/N): N
52
price: 6.31
58
price: 6.97
3
price: 5.77
9
price: 5.92
14
price: 5.67
  C-c C-cTraceback (most recent call last):
  File "./sample89.py", line 26, in <module>
    time.sleep(s)
KeyboardInterrupt
$

0 コメント:

コメントを投稿