“或”的问题在“day.weekday() == 5 或 6”中

发布于 2025-01-14 14:32:12 字数 234 浏览 2 评论 0原文

为什么在这种情况下使用“或”运算符会产生不同的结果?为什么我必须写两次 day.weekday() 而不仅仅是 == 5 或 6


这是有效的选项

if day.weekday() == 5 or day.weekday() == 6: 

这是给出不同结果的选项

if day.weekday() == 5 or 6:

Why does using the 'or' operator give different results in this case? Why must I write the day.weekday() twice rather than just == 5 or 6


This is the option that works

if day.weekday() == 5 or day.weekday() == 6: 

This is the option that gives a different result

if day.weekday() == 5 or 6:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉风有信 2025-01-21 14:32:12

或者语句的工作方式如下:

if (condition) or (condition):

通过说:

if day.weekday() == 5 or 6:

代码认为您暗示 6 是一个条件,如果您尝试在星期六打印某些内容(因为星期六是一周的第 6 天),则不会打印任何东西。希望这对您有所帮助,如果没有,请发表评论,否则您需要其他帮助。

Or statements work as such:

if (condition) or (condition):

By saying:

if day.weekday() == 5 or 6:

The code thinks that you are implying that 6 is a condition, which if you are trying to print something if it's a Saturday (since saturday is the 6th day of the week), you won't get anything printed. Hope this helps, leave a comment if it doesn't, or you need additional help.

丑疤怪 2025-01-21 14:32:12

它给出了不同的结果,因为“day.weekday() == 5”和“6”是分开计算的。它不会给出错误,因为任何非 0 的数字都会计算为“True”。

更好的写法是:

if day.weekday() in (5, 6):

It gives a different result because "day.weekday() == 5" and "6" are being evaluated separately. It doesn't give you an error because any number that is not 0 evaluates to "True".

The better way to write this would be:

if day.weekday() in (5, 6):
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文