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.
This is weird for a code that is so simple. I've tested on 2 computers. 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)
On Python 2, /
defaults to truncating integer division when passed int
operands, not "true division" (which produces float
results). 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) 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.)
since ang
is probably an integer small enough then 3 * abs(ang) / 360
is an expression where one integer divides another.
Python 2 division is integer division by default so the result is probably 0.
Fix:
3.0 * abs(ang) / 360
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.