不能让指数在我的计算器中工作

时间:2013-05-19 16:29:57

标签: python calculator

这是我第一次在python ......或者任何其他编程语言中做任何事情。

以下是我第一次尝试使用简单的计算器:

print ("Hello")
def calc():
    x = int(input("Input first integer: "))
    y = int(input("Input second integer: "))
    type = str.lower(input("(A)dd, (S)ubstract, (M)ultiply, (D)ivide \n"))
    if type != "a" and type != "s" and type != "m" and type != "d":
        print ("Sorry, the command you entered is not valid.")
        calc()
    else:
        if type =="a":
            print ("The result is '" + str(x+y) + "'")
        elif type == "s":
            print ("The result is '" + str(x-y) + "'")
        elif type =="m":
            print ("The result is '" + str(x*y) + "'")
        elif type == "d":
            print ("The result is '" + str(float(x)/float(y)) + "'")

        if int(input("Enter 1 if you would like to perform another calculation? \n")) == 1:
            calc()
        else:
            exit()
calc()

这似乎工作正常。接下来我尝试将指数和余数添加到混合中,我得到语法错误。

print ("Hello")
def calc():
    x = int(input("Input first integer: "))
    y = int(input("Input second integer: "))
    type = str.lower(input("(A)dd, (S)ubstract, (M)ultiply, (D)ivide,       (E)xponent,      (R)emainder\n"))
if type != "a" and type != "s" and type != "m" and type != "d" and type != "e" and type != "r":
    print ("Sorry, the command you entered is not valid.")
    calc()
else:
    if type == "a":
        print ("The result is '" + str(x+y) + "'")
    elif type == "s":
        print ("The result is '" + str(x-y) + "'")
    elif type == "m":
        print ("The result is '" + str(x*y) + "'")
    elif type == "d":
        print ("The result is '" + str(float(x)/float(y)) + "'")
    elif type == "e":
        print ("The result is '" + str(x**y + "'")
    elif type == "r":
        print ("The result is '" + str(x%y) + "'")

    if int(input("Enter 1 if you would like to perform another calculation? \n")) == 1:
        calc()
    else:
        exit()
calc()

有什么简单的我做错了吗? 另外,我需要添加一个“Q”来退出......任何人都可以向我推荐一些可以更简单地解释这个过程的东西吗?

2 个答案:

答案 0 :(得分:1)

print ("The result is '" + str(x**y + "'")

缺少括号

答案 1 :(得分:0)

递归调用不是最佳的,就像你保持运行一样,多次使用后会出现堆栈溢出!

而是在主逻辑中进行循环

while True:

    calc();