-1

我在 python 中编写了一个小型控制台计算器:

def calculator(num1=0, num2=0):
    conta = input("Type operation(+,x,/ or -:)")
    if (conta == "+"):
        print("Result:" + repr(num1) + " + " + repr(num2) + " is " + str(num1 + num2))
    elif (conta == "-"):
        print("Result:" + repr(num1) + " - " + repr(num2) + " is " + str(num1 - num2))
    elif (conta == "x"):
        print("Result:" + repr(num1) + " x " + repr(num2) + " is " + str(num1 * num2))
    elif (conta == "/"):
        print("Result: " + repr(num1) + " + " + repr(num2) + " is " + str(num1 / num2))
    else:
        print("Result:" + repr(num1) + conta + repr(num2) + " is Are you Joking?")

try:
    num1 = float(input("Type a number:"))
    num2 = float(input("Type a number:"))
    calculator(num1, num2)
except:
    print("Error.")
    exit()

它在 IDLE Shell 中正常工作。我放:

500.65 + 300 = 700.65
12 joke 12 = Are you Joking?

然后......当我从 .PY 文件加载它时,它会询问一个数字。我放了。问另一个。放吧。要求手术。我放了一个。窗口关闭。

现在我尝试在 Python 控制台上运行它。回报:

第 1 行中的 SyntaxError => 无效语法。

那么,怎么了?我能做些什么?

4

2 回答 2

4

主要问题是错误的缩进。

此外,您可能希望使用operator模块将用户定义的字符串映射到数学运算:

import operator


def calculator(num1, num2, op):
    op_map = {'+': operator.add,
              '-': operator.sub,
              'x': operator.mul,
              '/': operator.div}

    if op not in op_map:
        raise ValueError("Invalid operation")

    return op_map[op](num1, num2)

num1 = float(input("Type a number:"))
num2 = float(input("Type a number:"))
op = input("Type operation (+,x,/ or -):")

print(calculator(num1, num2, op))

演示:

Type a number:10
Type a number:10
Type operation(+,x,/ or -):+
20.0

Type a number:10
Type a number:10
Type operation (+,x,/ or -):illegal
Traceback (most recent call last):
  File "/home/alexander/job/so/test_mechanize.py", line 19, in <module>
    print calculator(num1, num2, op)
  File "/home/alexander/job/so/test_mechanize.py", line 11, in calculator
    raise ValueError("Invalid operation")
ValueError: Invalid operation
于 2013-09-07T18:54:03.777 回答
0

要在 python 读取 eval 循环中运行脚本,您应该执行类似的操作

>>> import script
于 2013-09-07T18:59:37.157 回答