You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HackerRank Python if-else题目代码问题:偶数大于20判断失效求助

Troubleshooting Your Py-If-Else HackerRank Problem

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) with 2 <= N <=5: This explicitly checks if N falls 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) with 6 <= N <=20: This correctly checks if N is between 6 and 20 (inclusive), covering the even numbers that should be labeled "Weird".
  • Now, when N is an even number greater than 20, it will skip all previous branches and hit the final elif, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:24:24