電卓を作ろう(1)
30分プログラム、その359。PythonでGUIな電卓を作ってみよう。
とりあえず、ロジック部分にチャレンジしてみたけど、結構難しい。誰か状態遷移図書いてないかな。
使い方
$ python calc.py >>1 1 >>+ 1 >>2 2 >>+ 3 >>3 3 >>= 6
ソースコード
#! /usr/bin/python # -*- mode:python; coding:utf-8 -*- # # calc.py - # # Copyright(C) 2008 by mzp # Author: MIZUNO Hiroki / mzpppp at gmail dot com # http://howdyworld.org # # Timestamp: 2008/09/02 21:47:05 # # This program is free software; you can redistribute it and/or # modify it under MIT Lincence. # import operator class Calc: def __init__(self): self.value = 0 self.op = lambda x,y: y self.input = 0 def eval(self,c): if c.isdigit(): self.input = self.input*10 + int(c) return self.input elif c == '+': self.value = self.op(self.value,self.input) self.input = 0 self.op = operator.add return self.value elif c == '=': self.value = self.op(self.value,self.input) self.input = 0 self.op = lambda x,y: y return self.value def __repr__(self): return "<Calc: value=%d op=%s input=%d>" % (self.value,self.op,self.input) if __name__ == '__main__': calc = Calc() try: while True: x= calc.eval(raw_input('>>')) print x except EOFError: pass