0

这是我第一次在 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”来退出......任何人都可以向我推荐一些更简单地解释这个过程的东西吗?

4

2 回答 2

1

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

缺少一个括号

于 2013-05-19T16:31:59.467 回答
0

递归调用不是最优的,因为如果你保持它运行,多次使用后会有堆栈溢出!

而是在主逻辑中循环

while True:

    calc();
于 2013-05-19T16:35:55.097 回答