Python中if语句如何匹配多个值?Khan Academy日期校验挑战代码问题求助
Hey there! Let's break down your Python date validation issues and fix them up step by step.
1. Why Your Expected Error Message Isn't Showing Up?
The core issue in your code is this line:
if day == 31 and month == not_31_days:
not_31_days is a tuple containing multiple month numbers ((4, 6, 9, 11)), but you're comparing a single integer month directly to this tuple with ==—this condition will never be true! That's why your custom error message isn't triggering, and instead you're seeing Khan Academy's default prompt for that scenario.
To fix this, use the in keyword to check if the month exists within the tuple of non-31-day months:
# Remove the trailing comma for cleaner syntax (it works either way, but this is more standard) not_31_days = (4, 6, 9, 11) if day == 31 and month in not_31_days: print("Error. Day must be within the month.")
As a small bonus optimization: Your current code asks for the month even if the user enters an invalid day first. You can add exit() after error messages to stop the program early and avoid unnecessary inputs:
if day < 1 or day > 31: print("Error. Day must be between 1 and 31.") exit()
2. How to Check for Multiple Values in Python if Statements
There are two common, readable ways to match a value against multiple candidates:
- Use
inwith a tuple/list/set (the most recommended approach):
This is concise and easy to maintain, especially as the number of candidates grows. For example:
For even faster lookups (with large candidate lists), use a set:# Tuples are great for fixed sets of values if month in (4, 6, 9, 11): # Execute logic for 30-day monthsnot_31_days = {4, 6, 9, 11} if month in not_31_days: # Execute logic - Chain conditions with
or(only ideal for very small sets of values):
This is more verbose but explicit for a tiny number of checks:if month == 4 or month == 6 or month == 9 or month == 11: # Execute logic
Full Corrected Code Example
Here's your code with all fixes applied, plus the early exit optimization:
day = int(input("Enter a day (1-31): ")) if day < 1 or day > 31: print("Error. Day must be between 1 and 31.") exit() month = int(input("Enter a month (1-12): ")) if month < 1 or month > 12: print("Error. Month must be between 1 and 12.") exit() not_31_days = (4, 6, 9, 11) if day == 31 and month in not_31_days: print("Error. Day must be within the month.")
Now when you input April (month 4) and day 31, your custom error message will trigger as expected.
内容的提问来源于stack exchange,提问作者nathan

