HackerRank Python if-else题目代码问题:偶数大于20判断失效求助
Hey there! Let's break down why your final elif branch isn't working, and fix it up step by step.
The Core Issue
Your problem comes from using range(6,20) and range(2,5) directly in your conditional checks. In Python, a range object is always considered "truthy" (evaluates to True) in a boolean context—even if the range doesn't include your number! So when you write num == 0 and range(6,20), this condition will always be True for any even number, because the range part doesn't actually check if N is inside that range. That means any even number ≥6 will trigger the second elif branch, even if it's greater than 20—so your final branch never gets a chance to run.
Fixed Code
Here's the corrected version that follows the problem's logic properly:
if __name__ == '__main__': N = int(input()) num = N % 2 if num > 0: print("Weird") elif num == 0 and 2 <= N <= 5: print("Not Weird") elif num == 0 and 6 <= N <= 20: print("Weird") elif num == 0 and N > 20: print("Not Weird")
What Changed?
- Replaced
range(2,5)with2 <= N <=5: This explicitly checks ifNfalls between 2 and 5 (inclusive), which matches the problem's requirement for even numbers in that range to be "Not Weird". - Replaced
range(6,20)with6 <= N <=20: This correctly checks ifNis between 6 and 20 (inclusive), covering the even numbers that should be labeled "Weird". - Now, when
Nis an even number greater than 20, it will skip all previous branches and hit the finalelif, printing "Not Weird" as expected.
Alternatively, you could use N in range(2,6) for the 2-5 check (since range(2,6) includes 2,3,4,5) and N in range(6,21) for 6-20 (since range(6,21) goes up to 20), but using direct comparison is often more readable for simple ranges like this.
内容的提问来源于stack exchange,提问作者Mittnick

