“SyntaxError:语法无效”,但之前有效! (Python 3.5.2为初学者做教程)

时间:2016-10-06 02:41:52

标签: python

所以我发誓这个代码以前工作过!

IDLE上是否有可能意外打开的设置?

我正在尝试做一些非常简单的事情。设置变量。

你可以看到这些工作:

>>> print("hello")
hello



>>> def main():
        print("hey")


>>>main()
hey

因此,当我尝试重新创建示例问题时,您会期望这些变量正常工作,对吗?

def main():
    print("This calculates the cost of coffee.")
    print()
    n = eval(input("Enter amount of coffee in pounds: ")
    m = 10.50 * n

SyntaxError: invalid syntax

为什么???为什么Python 3.5.2会返回“SyntaxError:invalid syntax”?

谢谢你们!对不起我就是这样的菜鸟。

1 个答案:

答案 0 :(得分:0)

正如评论中多次指出的那样,您只是错过了程序第4行的结束)。第4行应该看起来像

n = eval(input("Enter amount of coffee in pounds: "))# <--extra parenthesis

代码中的一些不相关的点:

  • 您为什么使用eval()?看起来您要进行浮点/整数转换,因此请使用int()float()
  • 只需说出print("This calculates the cost of coffee.\n")
  • ,而不是添加额外的印刷品来实现换行
  • 您的程序的最后两行可以压缩为一个语句:n = float(input("Enter amount of coffee in pounds: "))*10.50

将我的建议添加到您的代码后,它会产生如下内容:

def main():
    print("This calculates the cost of coffee.\n")
    n = float(input("Enter amount of coffee in pounds: "))*10.50