Python實現的簡單計算器

Python實現的簡單計算器

GUI執行截圖:

目錄

上面那個簡單的UI是用PyQt4實現的,如果對Qt比較熟悉的話,非常容易上手。

比如:

PyQt4裡的單行文字框:

self.line_edit = QtGui.QLineEdit()  # create an object of single line edit box
self.line_edit.text()  # get texts in the edit box
self.line_setText("text")  # set the text of edit box

還有Qt的佈局:

self.main_layout = QtGui.QGridLayout()
# add layouts
self.main_layout.addLayout(self.edit_line_layout, 0, 0)
self.main_layout.addLayout(self.button_layout, 1, 0)
# set layout to window
self.setLayout(self.main_layout)

這些跟QT的用法一樣,由於python的語法,寫起來很簡潔。

對於這個小東西,還有一點可以說的就是,異常處理。

下面是從字尾表示式得出計算結果的函式:

#calculate from stack, return result string
def calculate_from_stack(suffix_stack):
error_str = "error"
nan_str = "NaN"
if None == suffix_stack:
print "stack is empty!"
return error_str
data = suffix_stack.get_data()
calculate_stack = ExpStack.ExpStack()
for ele in data:
if is_number_str(ele):
calculate_stack.push(ele)
elif is_calculator_option(ele):
if calculate_stack.size() < 2:
print "Wrong suffix exps."
print_calculator_stack(suffix_stack)
return error_str
try:
num1 = float(calculate_stack.get_top())
calculate_stack.pop()
num2 = float(calculate_stack.get_top())
calculate_stack.pop()
if " " == ele:
calculate_stack.push(num1 num2)
elif "-" == ele:
calculate_stack.push(num2-num1)
elif "*" == ele:
calculate_stack.push(num2*num1)
elif "/" == ele:
calculate_stack.push(num2/num1)
elif "^" == ele:
calculate_stack.push(num2**num1)
else:
print "Unknown calculator operator", ele
return error_str
except TypeError, e:
print "type error:", e
return error_str
except ValueError, e:
print "value error:", e
return error_str
except ZeroDivisionError, e:
print "divide zero error:", e
return nan_str
if 1 == calculate_stack.size():
return str(calculate_stack.get_top())
else:
print "Unknown error, calculate stack:"
print_calculator_stack(calculate_stack)
return error_str

由於python是弱型別的語言,我直接把棧裡的字串拿出來,轉化為float進行運算,然後又壓入棧中。

這樣基本上不會因為資料型別的問題而頭疼(之前用C 寫的時候,因為型別問題,而開了兩個棧,一個存運算子,一個存數字,那麻煩程度,不用多說),即使由於float()函式產生異常,用try-except語句也能輕鬆搞定,並且語法還比java,C 的try-catch要簡潔。Python這麼好用,為什麼大學裡不開設這門課呢?反而大部分同學程式設計入門都是學的比Python深奧的多的C,C ,因為Python太簡單了嗎?

總體來說,用python寫程式真讓人輕鬆不少。

以上原始碼下載地址:http://download.csdn.net/detail/he_qiao_2010/6992511

我所用的Python IDE:http://www.jetbrains.com/pycharm/