Cal*_*oth 3 python return function
我现在的脚本中有以下功能:
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
Run Code Online (Sandbox Code Playgroud)
我的所有函数都使用这个系统在最后返回True,这是因为有一个中心函数按顺序运行每个函数并检查它们是否在执行下一个函数之前正确运行.
但是,当我运行脚本时,在我输入值以启动脚本之前,我收到以下错误:
File "C:\Users\Callum\Desktop\Tempus\TempusTest.py", line 59
return True
^
Run Code Online (Sandbox Code Playgroud)
如果我在IDLE中创建一个返回True的函数并检查它,它工作正常,但由于某种原因它不在我的脚本中
你们有没有想过为什么会这样?
谢谢!:)
Rik*_*ggi 12
你错过了一个括号.
您需要更改此行:
date_in_history = date.today() - timedelta(days=(p_year * 365)
Run Code Online (Sandbox Code Playgroud)
有:
date_in_history = date.today() - timedelta(days=(p_year * 365))
^
|
it was this one :)
Run Code Online (Sandbox Code Playgroud)
问:为什么它在返回线上显示错误而不存在?
因为错误实际上存在.
Python怎么会知道你不会timedelta在下一行给出另一个合法的论点?
或添加+100到(p_year * 365)?(像帝斯曼建议的那样)
我们来看看这个IDE会话:
>>> t = ('one', 'two',
... 'three'
... def f(): pass
File "<stdin>", line 3
def f(): pass
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
IDE无法知道我的元组已完成,我不会添加'fourth'元素.
你可能想扮演魔鬼的拥护者,并说我没有输入逗号,所以Python应该猜到我将结束那里的元组.
但是看看另一个例子:
>>> t = ('one', 'two',
... 'three'
... 'fourth')
>>>
>>> t
('one', 'two', 'threefourth')
Run Code Online (Sandbox Code Playgroud)
因此,当您return True在不应该出现的地方遇到Python时,您会看到错误发生的错误.