[英]Having an issue with time.sleep in python 2.7
I'm running this very simple function for testing: 我正在运行此非常简单的功能进行测试:
import time
def printnum(ang):
if ang > 0:
print(ang)
time.sleep(3 * abs(ang) / 360)
print("done")
if ang < 0:
print(ang)
time.sleep(3 * abs(ang) / 360)
print("done")
When I run it on python 3 it works fine However, on python 2 I get an issue where printnum
doesn't work on a wide range of numbers, it doesn't perform the delay... In fact, so far it has only worked with printnum(180)
in my tests. 当我在python 3上运行时,它可以正常工作。但是,在python 2上,我遇到了一个问题,即printnum
不能在广泛的数字上运行,它没有执行延迟...实际上,到目前为止,它仅具有在我的测试中使用了printnum(180)
。
This is weird for a code that is so simple. 对于这么简单的代码,这很奇怪。 I've tested on 2 computers. 我已经在2台计算机上进行了测试。 Does it happen to you? 你有事吗 Any reason why? 有什么原因吗? Suggestions to make it work? 建议使其工作? (Other than moving to python 3 which is hard on the hardware I'm working with) (除了转向在我正在使用的硬件上很难使用的python 3之外)
On Python 2, /
defaults to truncating integer division when passed int
operands, not "true division" (which produces float
results). 在Python 2上, /
传入int
操作数时默认为截断整数除法,而不是“ true除法”(产生float
结果)。 You can fix in one of two ways: 您可以采用以下两种方式之一进行修复:
from __future__ import division
to the top of the file to use Python 3 division rules ( /
means true division always, where you use //
if you really mean floor division) from __future__ import division
添加到文件顶部以使用Python 3分区规则( /
始终表示真正的分区,如果真的表示地板分区,则始终使用//
) 3
or 360
to float
literals so the math is performed float
-style, eg time.sleep(3. * abs(ang) / 360)
or time.sleep(3 * abs(ang) / 360.)
将3
或360
更改为float
文字,以便以float
样式执行数学运算,例如time.sleep(3. * abs(ang) / 360)
或time.sleep(3 * abs(ang) / 360.)
since ang
is probably an integer small enough then 3 * abs(ang) / 360
is an expression where one integer divides another. 因为ang
可能是一个足够小的整数,所以3 * abs(ang) / 360
是一个整数除以一个整数的表达式。
Python 2 division is integer division by default so the result is probably 0. Python 2除法默认为整数除法,因此结果可能为0。
Fix: 固定:
3.0 * abs(ang) / 360
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.