Python 如何在 if 语句中判断一个变量是否匹配多个值?
数据小许
使用 in 检查月份是否在指定的值中,把条件改成:
if day == 31 and month in not_31_days:
print("Error. Day must be within the month.")
当日期为 31,且月份为 4、6、9 或 11 时,代码就会输出错误提示。
为什么原来的条件不成立?
这行代码创建了一个包含四个整数的 tuple(元组):
not_31_days = 4, 6, 9, 11,
逗号使这些值组成元组,末尾的逗号可以保留。也可以加上括号,让元组更容易辨认:
not_31_days = (4, 6, 9, 11)
month == not_31_days 比较的是整数与整个元组是否相等。例如,月份为 4 时,相当于判断 4 == (4, 6, 9, 11),结果为 False。
month in not_31_days 检查的是元组中是否包含这个月份,符合题目的要求。
完整代码怎么写?
按题目贴出的格式,if 后面的 print 缺少缩进,需要一起修正。下面的代码使用 if 和 elif,依次检查日期范围、月份范围,以及指定月份是否出现 31 日:
day = int(input("Enter a day (1-31): "))
month = int(input("Enter a month (1-12): "))
not_31_days = (4, 6, 9, 11)
if day < 1 or day > 31:
print("Error. Day must be between 1 and 31.")
elif month < 1 or month > 12:
print("Error. Month must be between 1 and 12.")
elif day == 31 and month in not_31_days:
print("Error. Day must be within the month.")
当 day 为 31、month 为 4 时,前两个条件都不成立,最后一个条件成立,因此会输出:
Error. Day must be within the month.
用 or 判断可以吗?
可以,但需要为每个月份写出完整的比较,并用括号把月份条件组合起来:
if day == 31 and (month == 4 or month == 6 or month == 9 or month == 11):
print("Error. Day must be within the month.")
不要写成 month == 4 or 6 or 9 or 11。这个表达式不会把 month 分别与四个值比较,其中非零整数会被当作真值,导致条件不符合预期。对于这组固定值,用 in 更清楚。
这段校验有哪些限制?
代码只处理题目要求的四个月份及基本数值范围,没有检查 2 月的天数和闰年。另外,int(input(...)) 要求输入能转换为整数。如果输入字母等内容,会触发 ValueError,需要另行处理。
备注:内容仅供参考。
