简体   繁体   English

无法弄清楚条件

[英]Cant figure out conditionals

I'm working on a 30 day of code challenge and passed 5/8 tests on my code and can't figure out the reason it keeps failing我正在进行 30 天的代码挑战,并通过了 5/8 的代码测试,但无法弄清楚它一直失败的原因

The parameters are that if N is odd print weird, if N is even and in the range of 2-5 print not weird if N is even and in the range of 6-20 print weird if N is even and greater than 20 print not weird参数是如果 N 是奇数打印怪异,如果 N 是偶数并且在 2-5 范围内打印不奇怪如果 N 是偶数并且在 6-20 范围内打印怪异如果 N 是偶数并且大于 20 打印不诡异的

N = int(input())

if  N % 2 == 0 and range(2-5): 
    print("Not Weird")
elif N % 2 == 0 and range(6-20): 
    print("Weird")
elif N % 2 == 0 and N > 20:
    print("Not Weird")
elif N % 2 == 1 :
    print("Weird")
if  N % 2 == 0 and range(2-5): 

does not do what you think, it should instead be something like:不做你想的,它应该是这样的:

if  N % 2 == 0 and N in range(2, 6): 

Specifically:具体来说:

  • each sub-condition (on either side of your 'and') should be complete.每个子条件(在“和”的任一侧)都应该是完整的。
  • range, in your example, was range(-3) since that's what 2-5 gives.在您的示例中,范围是 range(-3) ,因为这是 2-5 给出的。
  • the range is half open, meaning it includes the start but excludes the end.范围是半开的,这意味着它包括开始但不包括结束。

1) The function range with defined begging and end is a function that takes 2 parameters as argument. 1) 定义了 begging 和 end 的 function range是一个 function,它以 2 个参数作为参数。 Therefore I'd recommend you to use it as range(x,y) instead of range(xy) .因此,我建议您将其用作range(x,y)而不是range(xy)

If you use it like range(2-5) , you're actually asking for range(-3) .如果你像range(2-5)一样使用它,你实际上是在要求range(-3) When used with only 1 arg, the function range will give you a list of int from 0 up to the input arg .当仅与 1 个 arg 一起使用时,function range将为您提供从 0 到输入 argint列表。

Regarded that there is no integer greater than 0 and less than -3 , then you're getting an empty list.考虑到没有大于 0小于 -3的 integer ,那么您将得到一个空列表。

2) Also, notice that the upper limit is not inclusive: 2)另外,请注意上限不包括在内:

>>> for i in range(2,5):
...     print(i)
... 
2
3
4

so you might consider to use range(2,6) for the first case, range(6,21) for the second case and so on and so forth..所以你可以考虑对第一种情况使用range(2,6) ,对第二种情况使用range(6,21) ,依此类推..

To expand on @paxdiablo's answer, you can also use the step argument of range to test for even numbers:要扩展@paxdiablo 的答案,您还可以使用rangestep参数来测试偶数:

if N in range(2, 6, 2):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM