有没有一种方法可以将随机数明确定义为变量以在函数中使用它?

时间:2019-08-27 09:50:56

标签: python random

我不能清楚地使用随机int作为变量来在我的代码中进行比较。不管产生的随机数如何,似乎只会抛出第一个if语句。

from random import randint
rate = randint(0, 255)
wind = rate
print(rate)
if wind > 251:
    print("The hurricane is a category 5!")
elif wind <= 251 or wind >= 209:
    print("The hurricane is a category 4!")
elif wind <= 208 or wind >= 178:
    print("The hurricane is a category 3!")

该代码假定使用一定范围内的随机数来确定飓风等级并打印有关消息。代码在一定程度上有效。 无论脚本产生的随机数是什么,都不会出现错误消息,只是始终打印类别4行

1 个答案:

答案 0 :(得分:0)

rate的值介于0到255 rate = randint(0, 255)

风速等于速率wind = rate

第一个条件检查风是否大于251,这将从不为真,因为其在0到250 if wind > 251:之间的随机值

第二个条件检查风是否小于251,因为它在0 {elif wind <= 251

之内是随机的,因此总是

可能的修复:也许您打算在条件中使用and而不是or