簡體   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