猿问

谁能帮我完成这个 python-if-else 任务?

import random


n = 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")    

这段代码有问题吗?


拉风的咖菲猫
浏览 85回答 2
2回答

Cats萌萌

您的范围检查并不严格,例如:包括andrange(2, 5)之间的整数,但无论如何有一种更简单的方法来编写它;尝试这个:24import random&nbsp; &nbsp;&nbsp;n = random.randint(1,100)if n % 2 != 0:&nbsp; &nbsp; print("Weird")elif 2 <= n <= 5: # from this point on, the number can only be even&nbsp; &nbsp; print("Not Weird")elif 6 <= n <= 20:&nbsp; &nbsp; print("Weird")elif n > 20:&nbsp; &nbsp; print("Not Weird")或者更好的是,它更简单并且做同样的事情:if n % 2 != 0 or 6 <= n <= 20:&nbsp; &nbsp; print("Weird")else:&nbsp; &nbsp; print("Not Weird")

富国沪深

随机导入n = random.randint(1,100)print(n)if (n % 2 != 0):&nbsp; &nbsp; print("Weird")elif (n % 2 == 0 and n in range(2,5)):&nbsp; &nbsp; print("Not Weird")elif (n % 2 == 0 and n in range(5,20)):&nbsp; &nbsp; print("Weird")elif (n % 2 == 0 and n >= 20):&nbsp; &nbsp; print("Not Weird")您缺少一些范围,我刚刚更新了代码尝试一下。
随时随地看视频慕课网APP

相关分类

Python
我要回答