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

时间:2022-12-29 14:35:12
#!/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