简体   繁体   中英

Converting float to hexadecimal in python

So, I'm trying to convert this Scratch program to a python program: http://scratch.mit.edu/projects/1963078/#editor . I am currently using it with pattern 3. Here's what I have:

from turtle import*
import random
import math
turtle = Turtle()
bgcolor("#000000")
ht()
speed(0)
goto(0,0)
def draw():
    x1 = (random.randint(0,250))
    y1 = (random.randint(0,250))
    x2 = (random.randint(0,250))
    y2 = (random.randint(0,250))
    counts = 0
    while counts < 250:
        count = 0
        while count<250:
            c = (math.tan(math.sqrt(((xcor() - x1)**2) + ((ycor() - y1)**2))))*(math.tan(math.sqrt(((xcor() - x2)**2) + ((ycor() - y2)**2))))
            color(c)
            setx(xcor+1)
            count += 1
        counts +=1
draw()

I know a lot of people use python 2, but I'm using 3. The problem right now is that when it uses that long line to generate a color, it's returning a decimal number, when I need to be getting a hex code. Any tips on how I would convert that to get a result like the scratch project? Thanks!

There isn't any standard method for converting a floating point / decimal number to hex (usually hex is only used for positive integers)… so you'll have to decide how you want to convert the decimal to a positive integer.

BUT, once you've got a positive integer, you can convert that to an RGB hex color (ex, #AABBCC ) using:

>>> some_number = 123456
>>> hex_color = "#%06X" %(some_number, )
>>> print hex_color
#01E240

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM