【问题标题】:'Syntax Error' when returning True on Python 3.2在 Python 3.2 上返回 True 时出现“语法错误”
【发布时间】:2012-03-09 20:47:25
【问题描述】:

此刻我的脚本中有以下功能:

def _convert_time(p):
    """Converts a percentage into a date,
    based on current date."""

    # This is the number of years that we subtract from
    # the current date.
    p_year = pow(math.e, (20.344 * pow(p, 3) + 3)) - pow(math.e, 3)

    # Returns in YYYY-MM-DD format
    date_in_history = date.today() - timedelta(days=(p_year * 365)

    # Return to the control loop
    return True

我所有的函数都使用这个最后返回 True 的系统,这是因为有一个中心函数依次运行每个函数,并在执行下一个函数之前检查它们是否正确运行。

但是,当我运行脚本时,在我输入一个值来启动脚本之前,我收到以下错误:

 File "C:\Users\Callum\Desktop\Tempus\TempusTest.py", line 59
 return True
      ^

如果我在 IDLE 中创建一个返回 True 的函数并检查它,它工作正常,但由于某种原因它不在我的脚本中

你们对为什么会这样有任何想法吗?

谢谢! :)

【问题讨论】:

  • 如果没有返回值(或者至少,它不依赖于任何东西),我建议你放弃返回True的系统,并坚持'return'。如果发生一些意外行为,我认为最好改为引发错误。换句话说,如果上述两个赋值没有出错,则始终返回 True,因此 True 是......没有意义。但是,如果发生错误,它将无法处理并停止。特别是因为您正在检查返回的“真”,它在风格上也违背了 Python 的“先行动,稍后道歉”的优点(假设值会起作用,如果不好则捕获)

标签: python function return


【解决方案1】:

你缺少一个括号。

你需要改变这一行:

date_in_history = date.today() - timedelta(days=(p_year * 365)

与:

date_in_history = date.today() - timedelta(days=(p_year * 365))
                                                              ^
                                                              |
                                                       it was this one :)

问:为什么返回线上显示错误而不是那里?

因为错误确实存在。

Python 怎么知道你不会在下一行给出另一个合法的 timedelta 参数?
或者将+100 添加到(p_year * 365)(就像 DSM 建议的那样)

让我们看看这个 IDE 会话:

>>> t = ('one', 'two',
...      'three'
... def f(): pass
  File "<stdin>", line 3
    def f(): pass
      ^
SyntaxError: invalid syntax

IDE 无法知道我的元组已完成并且我不打算添加 'fourth' 元素。

你可能想扮演魔鬼的拥护者,说我没有输入逗号,所以 Python 应该猜到我会在那里结束元组。

但是看看另一个例子:

>>> t = ('one', 'two',
...      'three'
...      'fourth')
>>> 
>>> t
('one', 'two', 'threefourth')

因此,正如您所见,错误发生在 Python 在不应该出现的地方遇到 return True 时。

【讨论】:

  • 谢谢! :D 那么为什么它在返回线上显示错误而不在那里呢?
  • @CallumBooth:因为下一行可能是 + 100 之类的东西。您不需要在同一行关闭括号,因此它只会在返回时变成语法错误。一般来说,当一行中出现 SyntaxError 看起来不错时,通常是因为它前面有一个未终止的元素。
  • @Callum:DSM 已经为我解释了这一点,无论如何我已经改进了我的答案。
  • @DSM @Rik Poggi:谢谢,我只是有点搞不懂它为什么会在那里发生,谢谢你的解释!
  • @CallumBooth:不客气!如果这个答案解决了您的问题并消除了您的疑虑,也许您想accept它:)
【解决方案2】:

错误就在前面。

date_in_history = date.today() - timedelta(days=(p_year * 365)
                            10            1     2            1

date_in_history = date.today() - timedelta(days=(p_year * 365))
                            10            1     2            10

缺少一个右括号

【讨论】:

  • 详细说明这个答案:Python 不能告诉你哪里出错了,它只能告诉你哪里弄错了。由于如果括号打开,Python 会自动继续下一行的语句,因此它只会在表达式中间看到return(它认为仍然是)时才会感到困惑。
  • @kindall:词汇失败。 Python 并不混乱;它在第一个可能的标记处正确检测并报告语法错误。
  • 我正在拟人化。我知道计算机讨厌这样,但我无能为力。
猜你喜欢
  • 1970-01-01
  • 2020-06-11
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
相关资源
最近更新 更多