python - 生成随机 float

标签 python

现在我正在努力让 Python 在您的屏幕上“打字”(我感到无聊和实验),我靠自己走到了这一步,但我找不到任何在我的脚本中使用小数的方法,因为 Python 只接受 randint() 的整数。

#include <stdio.h>;
import sys;
import time;
import os;
import random;
os.system("clear");

script = "I just really need to type something right now. I'm not sure why, but I really feel like typing on the Chromebook right now. It seems kinda weird, but I like doing this. It helps me practice what I'm doing. I've noticed that I'm a lot worse at typing lately, and I don't know why. Maybe it's because I've been working with a chunky keyboard, and these Chromebook keyboards are extremely thin. Yup, this is actually entertaining for me. I'm not exactly sure why I want to do this, but I just do. It's almost addicting to me, and I don't know why.\n";

for i in range(0, 587):
sys.stdout.write(str(scripti));
sys.stdout.flush();
time_num = random.randint(0.1, 0.4);
time.sleep(time_num);

我得到的输出是:

ITraceback (most recent call last):
File "main.py", line 11, in <module>
time_num = random.randint(0.1, 0.4);
File "/usr/lib64/python2.7/random.py", line 242, in randint
return self.randrange(a, b+1)
File "/usr/lib64/python2.7/random.py", line 187, in randrange
raise ValueError, "non-integer arg 1 for randrange()"
ValueError: non-integer arg 1 for randrange()

有什么想法吗?

编辑:不要告诉我如何简化它,因为这只是为了学习。

最佳答案

为什么不使用随机均匀分布呢?在这种情况下,您可以获得非整数数值。使用:

import random
random.uniform(0.1,0.4)

关于python - 生成随机 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29314213/

相关文章:

python - Python 中的 XML 解析问题 - 找不到 findtext

python - 有没有办法通过使用 numpy 或其他资源来优化 Python 中的三重循环?

python - 在 python 中重新组合这两个列表的聪明方法

python - 无法安装 ROS - python2 setuptools 中出现错误

python - matplotlib 轴标签的奇怪错误

python - 处理错误: Not a directory python

python - py2neo 不在 Neo4j 数据库中强制执行唯一性约束

python - 在 matplotlib 中将错误栏添加到 3D 图

python - python3 十六进制的奇怪行为

python - 在 Keras 中使用自定义步骤激活函数会导致 “' tuple' object has no attribute '_keras_shape' ” 错误。如何解决这个问题?