【问题标题】:Is there a way to clearly define a random number as a variable to use it in a function?有没有办法将随机数明确定义为变量以在函数中使用它?
【发布时间】:2019-08-27 09:50:56
【问题描述】:

我不能清楚地使用随机 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 行

【问题讨论】:

  • ands替换你的ors

标签: python random


【解决方案1】:

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

风等于速率wind = rate

第一个条件检查风是否大于 251,这将永远为真,因为它是 0 到 250 之间的随机数if wind &gt; 251:

第二个条件检查风是否小于 251,这将 总是为真,因为它是 0elif wind &lt;= 251 内的随机数

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

【讨论】:

  • 另一个建议是这样写:if 178 &lt;= wind &lt;= 208 以防止将来出现此类错误。
  • 感谢@Umair Mohammed 的提示。我稍微更改了代码以将 randint 分配为 int。它奏效了。 from random import randint wind = randint(0, 255) calc_category = wind print(wind)
猜你喜欢
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多