Skip to main content
 首页 » 编程设计

python之如何解释这种随机的 python 行为

2025年05月04日26wuhuacong

这个小脚本生成一个介于 0 和 1 之间的随机 float ,然后如果它小于“0.000111111111111”,它将打印消息“found it”

import random 
 
value = 0.4 / 3600 
print value 
 
while True: 
    rand = random.random() 
 
    print "RAND IS: " + str(rand) + "----- VAL IS " + str(value) 
    if rand < value: 
        print "found it" 

所以看似脚本运行并且它从未真正“找到它”,但是当我在 if 语句之前注释掉 print 语句时,即使 rand 值不小于 value,命令行也会充满“found it” .什么鬼?

请您参考如下方法:

您的 while 循环被设计为永远运行,因为 True 始终是 True。你永远不会跳出那个无限循环。即使它找到了值,它也只是打印它,因为你给 while 循环的条件仍然是 True。由于无法更改条件,因此需要添加 break 语句:

while True: 
    rand = random.random() 
    print "RAND IS: " + str(rand) + "----- VAL IS " + str(value) 
    if rand < value: 
        print "found it" 
        break