gpt4 book ai didi

python django 返回不同的变量

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:53 25 4
gpt4 key购买 nike

我正在寻找一种方法来返回 True 或一个字符串,然后使用该信息来显示或不显示某些内容。这是我的代码:

def time_remaining(self):
timer = self.timer
now = datetime.datetime.utcnow().replace(tzinfo=utc)
if timer < now:
return True
else:
#Returns a timedelta in string
return game_logic.timedelta_format(timer - now)

然后我使用:

if time_remaining():
possible = True
else:
possible = False

return render(request, 'training.html',{'possible': possible})

最后在我的模板中:

{% if possible %}
<some html>
{% else %}
<different html>
{% endif %}

即使 time_remaining 返回字符串而不是 True,我总是以某种方式结束

我该如何解决这个问题?

最佳答案

在 Python 中,非空字符串也计算为 True:

>>> bool('foo')
True
>>> bool('')
False

因此无论您的 time_remaining 函数返回什么,它在您的 if 语句中总是被评估为 True

你可能想使用类似的东西:

time_remaining() == True

或者如果没有剩余时间,甚至可以让 time_remaining 返回 FalseNone(特别是如果您只打算使用输出time_remaining 在你的 if 语句中)。

关于python django 返回不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20353363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com