繁体   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')

我想这样工作:如果 N 是奇数,打印 Weird 如果 N 是偶数并且在 2 到 6 的包含范围内,打印 Not Weird 如果 N 是偶数并且在 6 到 20 的包含范围内,打印 Weird If N是偶数且大于 20,打印 Not Weird

您需要使用 mod 运算符来检查数字是否为奇数。

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

表达式N/2 == 0仅在N为零时为真,您需要模运算符:

if N % 2 == 0:

此外,表达式range(a, b)为您提供了ab - 1的包含范围,因此这些range调用并没有按照您的想法进行(无论如何,它们似乎重叠)。

无论如何我都会绕过它们,只使用更传统的表达方式,比如(检查范围,我不得不根据问题中不完整的细节做出假设——例如,你似乎不想为偶数打印任何东西少于两个 - 您可能想要确认该行为):

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')

这里面有两个问题:

1) 检查偶数或奇数,如果 N%2==0,则检查偶数或奇数。

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')

希望这可以帮助!

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