使用input()读取数据时出现语法错误



我一直试图在python GUI上编写一个简单的计算器,但收到了一条语法错误消息。我是编程新手,所以我不确定该做什么。

Traceback (most recent call last):
  File "C:Userskmart3223DesktopMartinez_K_Lab1.py", line 126, in <module>
    main()
  File "C:Userskmart3223DesktopMartinez_K_Lab1.py", line 111, in main
    operation = input("What operations should we do ( +, -, /, *):")
  File "<string>", line 1
    +
    ^
SyntaxError: unexpected EOF while parsing

代码

def main():
    operation = input("What operations should we do ( +, -, /, *):")
    if(operation != '+' and operation != '-' and operation != '/' and operation != '*'):
        print ("chose an operation")
    else:
        variable1 = int(input("Enter digits"))
        variable2 = int(input("Enter other digits"))
        if (operation == "+"):
            print (add(variable1, variable2))
        elif (operation == "-"):
            print (sub(variable1, variable2))
        elif (operaion == "*"):
            print (mul(variable1, variable2))
        else:
            print (div(variable1, variable2))
main()

如果您使用的是python 2x,请使用raw_input()

>>> input()         # only takes python expression
>>> input()
+
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    +
    ^
SyntaxError: unexpected EOF while parsing
>>> input()
'+'                 # string ok
'+'
>>> input()
7                   # integer ok
7
>>> raw_input()              # Takes input as string
+
'+'

使用raw_input()而不是input()

input()将输入的数据解释为Python表达式。raw_input()则返回您输入的字符串。

最新更新