您的位置:首页 > 编程语言 > Python开发

用python实现一个简单的计算器

2015-11-25 05:26 447 查看
#!/usr/bin/env python
#-*-coding: utf-8-*-

"a calculator"

print "My calculator version 1.0"
print "It's use is very easy"
print "Please enter some equation like 'number operator number'"
print "number could be integer or float"
print "operator could be '+' '-' '*' '/' '%' '**'"

def cal(arga, argb, oper):

if oper == "+":
return arga + argb

if oper == "-":
return arga - argb

if oper == "*":
return arga * argb

if oper == "/":
return arga / argb

if oper == "%":
return arga % argb

if oper == "**":
return arga ** argb

def get_pro():
while True:
get_in = raw_input("Please enter your equation: ")
if len(get_in) == 0:
print "No input: please enter a equation"
if len(get_in) > 0:
get_l = get_in.split()
return get_l

while True:
L = get_pro()
if len(L) != 3:
print "uninvalid input: please enter again"

if len(L) == 3:
num1 = L[0]
op = L[1]
num2 = L[2]

try:
int(num1) and int(num2)
except:
result = cal(float(num1), float(num2), op)
print "The result is %f"  % result
else:
result = cal(int(num1), int(num2), op)
print "The result is %d"  % result

choice = raw_input("Press any key to continue, press 'Q' or 'q' to quit: ")
if choice == "q" or choice == "Q":
print "Thanks for use!"
break
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: