这是什么语法错误?

时间:2013-09-07 18:48:25

标签: python syntax-error

我在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 =>语法无效。

那么,怎么了?我该怎么办?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在python read eval循环中运行脚本你应该做类似的事情

>>> import script