【问题标题】:"SyntaxError: Invalid Syntax" but it worked before! (Python 3.5.2 doing a tutorial for beginners)“SyntaxError: Invalid Syntax”,但它以前有效! (Python 3.5.2 为初学者做教程)
【发布时间】:2016-10-06 02:41:51
【问题描述】:

我发誓这段代码以前有效!

是否有我可能不小心打开的 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”?

谢谢各位!对不起,我是个菜鸟。

【问题讨论】:

  • 您在此行末尾缺少一个右括号:n = eval(input("Enter amount of coffee in pounds: ")。所以你需要这个:n = eval(input("Enter amount of coffee in pounds: ")))
  • 专业提示 - 不要使用 eval。在不使用 eval 的情况下,总有更好的方法来做到这一点。您看起来想将其转换为 int/float。所以改为:float(input("Enter amount of coffee in pounds: "))
  • 您在第 4 行末尾缺少括号 n = ...)

标签: python


【解决方案1】:

正如 cmets 多次指出的那样,您只是在程序的第 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2014-11-06
    • 2019-07-29
    • 2019-09-20
    • 2021-07-27
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多