简体   繁体   English

当 n 大于 20 时,它会打印“奇怪”,但应该打印“不奇怪”

[英]when n is greater than 20 it prints 'weird', but it should print 'not weird'

N = 24
if N/2 == 0:
    if N in range(2, 5):
        print('Not Weird')
    if N in range(6, 20):
        print('Weird')
    if N > 20:
        print('Not Weird')
if N/2 != 0:
    print('Weird')

I want to work it like this: If N is odd, print Weird If N is even and in the inclusive range of 2 to 6, print Not Weird If N is even and in the inclusive range of 6 to 20, print Weird If N is even and greater than 20, print Not Weird我想这样工作:如果 N 是奇数,打印 Weird 如果 N 是偶数并且在 2 到 6 的包含范围内,打印 Not Weird 如果 N 是偶数并且在 6 到 20 的包含范围内,打印 Weird If N是偶数且大于 20,打印 Not Weird

You need to use mod operator to check if the number is odd or not.您需要使用 mod 运算符来检查数字是否为奇数。

if N % 2 == 0:
    # do something
else:
    # do the other

The expression N/2 == 0 will only be true when N is zero, you want the modulo operator:表达式N/2 == 0仅在N为零时为真,您需要模运算符:

if N % 2 == 0:

Also, the expression range(a, b) gives you an inclusive range of a through to b - 1 , so those range calls aren't doing what you think (in any case, they seem to overlap).此外,表达式range(a, b)为您提供了ab - 1的包含范围,因此这些range调用并没有按照您的想法进行(无论如何,它们似乎重叠)。

I would bypass them anyway and just use more conventional expressions, something like (check the ranges, I've had to make assumptions based on incomplete details in the question - for example, you don't seem to want to print anything for even numbers less that two - you might want to confirm that behaviour):无论如何我都会绕过它们,只使用更传统的表达方式,比如(检查范围,我不得不根据问题中不完整的细节做出假设——例如,你似乎不想为偶数打印任何东西少于两个 - 您可能想要确认该行为):

N = 24
if N % 2 == 0:
    if N >= 2 and N < 6: # 2-5 inclusive
        print('Not Weird')
    elif N >= 6 and N < 21: # 6-20 inclusive
        print('Weird')
    elif N > 20:
        print('Not Weird')
else:
    print('Weird')

There are two issues in this:这里面有两个问题:

1) To check even or odd check if N%2==0, then even else odd. 1) 检查偶数或奇数,如果 N%2==0,则检查偶数或奇数。

2) You have used range() function, so if you give number 20, it wont give any output, because 20 is not in range(6,20). 2)你使用了range() function,所以如果你给数字20,它不会给任何output,因为20不在范围内(6,20)。

N = 20
if N%2 == 0:
    if N >= 2 and N<=5:
        print('Not Weird')
    if N >= 6 and N <= 20:
        print('Weird')
    if N > 20:
        print('Not Weird')
else:
    print('Weird')

Hope this helps!希望这可以帮助!

N = 24
if N%2 == 0:  # '%' returns the remainder after floor division
    if N in range(6, 21):  # range(6, 20) excludes 20
        print('Weird')
    else:
        print('Not Weird')  # you can also just use else here
else:  # use else because if it's not even, it is guaranteed to be odd
    print('Weird')

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

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