亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

誰能幫我完成這個 python-if-else 任務?

誰能幫我完成這個 python-if-else 任務?

拉風的咖菲貓 2022-06-02 15:18:19
import randomn = random.randint(1,100)if (n % 2 != 0):    print("Weird")elif (n % 2 == 0 and n in range(2,5)):    print("Not Weird")elif (n % 2 == 0 and n in range(6,20)):    print("Weird")elif (n % 2 == 0 and n > 20):    print("Not Weird")    這段代碼有問題嗎?
查看完整描述

2 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您的范圍檢查并不嚴格,例如:包括andrange(2, 5)之間的整數,但無論如何有一種更簡單的方法來編寫它;嘗試這個:24


import random    

n = random.randint(1,100)


if n % 2 != 0:

    print("Weird")

elif 2 <= n <= 5: # from this point on, the number can only be even

    print("Not Weird")

elif 6 <= n <= 20:

    print("Weird")

elif n > 20:

    print("Not Weird")

或者更好的是,它更簡單并且做同樣的事情:


if n % 2 != 0 or 6 <= n <= 20:

    print("Weird")

else:

    print("Not Weird")


查看完整回答
反對 回復 2022-06-02
?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

隨機導入


n = random.randint(1,100)

print(n)

if (n % 2 != 0):

    print("Weird")

elif (n % 2 == 0 and n in range(2,5)):

    print("Not Weird")

elif (n % 2 == 0 and n in range(5,20)):

    print("Weird")

elif (n % 2 == 0 and n >= 20):

    print("Not Weird")

您缺少一些范圍,我剛剛更新了代碼嘗試一下。


查看完整回答
反對 回復 2022-06-02
  • 2 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號