英文:
if statement returning same statement for all results rather than changing based on the if statement
问题
"Change day Sunday"
"Change day Thursday"
英文:
I'm trying to write a simple code that will tell me if the date that I need to do something falls on a weekend. When I run this code I get the "change day" regardless of the day of the week, there is obviously something wrong with the code but I can't see it
if week_Days[movePlates.weekday()] == "Saturday" or "Sunday":
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
if week_Days[readPlates.weekday()] == "Saturday" or "Sunday":
print("change day " + str(week_Days[readPlates.weekday()]))
else:
print("read plates on: " + str(readPlates))
Change day Sunday
Change day Thursday
答案1
得分: 0
这是隐式布尔结果的一个示例。要在你的if语句中添加括号(而不改变它):
if (week_Days[movePlates.weekday()] == "Saturday") or "Sunday":
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
问题在于你在or
语句中处理字符串"Sunday",其中任何非空字符串都为True,因此or
语句评估为True。这是一种解决方法:
if week_Days[movePlates.weekday()] == "Saturday" or week_Days[movePlates.weekday()] == "Sunday":
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
或者,如果你想使用不同的语法使其更简单,你可以这样做:
if week_Days[movePlates.weekday()] in ("Saturday", "Sunday"):
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
英文:
This is a result of implicit booleans. To add parentheses to your if statement (without changing it):
if (week_Days[movePlates.weekday()] == "Saturday") or "Sunday":
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
The problem is that you're treating the string "Sunday" in an or
statement, where any nonempty string is True, so the or
statement evaluates to True. Here's one solution:
if week_Days[movePlates.weekday()] == "Saturday" or week_Days[movePlates.weekday()] == "Sunday":
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
Or if you wanted to make it a little simpler with different syntax, you could do
if week_Days[movePlates.weekday()] in ("Saturday", "Sunday"):
print("change day " + str(week_Days[movePlates.weekday()]))
else:
print("move plates on: " + str(movePlates))
答案2
得分: 0
你需要在if语句中对变量进行两天的测试(或使用in()
运算符)。我建议将测试包装在一个函数中(如果大小写不固定,可以使用lower()
):
def IsWeekend(a):
return (a.lower() == "saturday" or a.lower() == "sunday")
英文:
You need to test the variable against both days in your if-clause (or use the in()
operator). I'd suggest wrapping the test in a function (and using lower()
if the casing is not fixed):
def IsWeekend(a):
return (a.lower() == "saturday" or a.lower() == "sunday")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论