SoFunction
Updated on 2024-11-13

Python draw random color python method analysis

Today, my teacher asked me a question about using the turtle library to draw a python with random colors, and the colors of each segment are different, so I wrote this code. The idea of this code is to store different colors in a dictionary, and then use a random number library to randomly generate the corresponding key to call these colors, thus achieving the effect of random colors.

import turtle
import random#Import Random Number Module for Random Colors
# Store the different colors as a dictionary with key as an integer from 1 to 6
colors = {1:'blue',2:'yellow',3:'red',4:'purple',5:'black',6:'green'}
(650,350,200,200)
()
(-250)
()
(25)
(-40)
for i in range(4):
    a = (1,7)# Get a random number and assign it to a
    (colors[a])#Select colors by indexing (colors are random)
    (40,80)
    a = (1,7)# Get a random number and assign it to a
    (colors[a])#Select colors by indexing (colors are random)
    (-40,80)
(40,80/2)
(40)
(16,180)
(40*2/3)
()

This is the result of the run

However, it's too much trouble to store the colors one by one, and the colors are too limited to black, green, blue, red, and yellow, which doesn't achieve the purpose of random colors, so I improved it as follows.

import turtle
import random  # Import random number module to implement random colors
(255)  # Change the mode of the color representation from [0-1] to [0-255].
# Define a module to generate colors
def colorchoose():
    a, b, c = (0, 256), (0, 256), (0, 256)
    color = (a, b, c)
    return color   # The return value is an rgb color
(650, 350, 200, 200) 
()
(-250)
()
(25)
(-40)
for i in range(4):
    (colorchoose())  # Call module to randomly generate rgb colors
    (40, 80)
    (colorchoose())  # Call module to randomly generate rgb colors
    (-40, 80)
(40, 80 / 2)
(40)
(16, 180)
(40 * 2 / 3)
()

The color transformation in this code depends directly on the three parameters of the rgb color, so I make them random in the range of 0-255. (Note: the default mode of the rgb color parameters in python is 0-1, and with turtle you need to convert the mode to 0-255 with the (255) statement, otherwise you will get an error.) The reason for the module is that it is too cumbersome to change the three parameters of the rgb color without stopping by assignment, so it is more effortless to call a module with the ability to generate a random color. The reason for defining a module is that it's too much trouble to keep changing the three rgb parameters by assigning values to them, so it's less effort to call a module that generates a random color.

See, is the random color feature implemented?

to this article on Python draw random color python method of analysis of the article is introduced to this, more related Python draw color python content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!