Python实现的简单计算器

时间:2022-12-29 14:53:18

GUI运行截图:

Python实现的简单计算器



上面那个简单的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写程序真让人轻松不少。

Python实现的简单计算器


以上源码下载地址:http://download.****.net/detail/he_qiao_2010/6992511

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