Deutsch English |
YOU LEARN HERE... |
how you can generate random numbers. Since chance plays an extremely important role in everyday life, you can use random numbers to simulate such processes on the computer. As with a throw of the dice, random numbers are usually equally distributed, i.e. they occur with the same frequency (probability). |
EXAMPLES |
You draw 40 stars and define their position in the turtle window with random numbers. To do this, you need the randint() function from the random module, which you must first import.
Program: from gturtle import * from random import randint def star(): startPath() repeat 5: forward(50) left(144) fillPath() makeTurtle() setFillColor("blue") hideTurtle() repeat 40: star() x = randint(-250, 250) y = randint(-250, 250) setPos(x, y) |
Program: from gturtle import * from random import randint def star(): startPath() repeat 5: forward(50) left(144) fillPath() makeTurtle() hideTurtle() clear("darkblue") repeat(50): star() r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) setFillColor(r, g, b) x = randint (-300, 300) y = randint (-250, 250) setPos(x, y) |
Program: from gturtle import * from random import randint makeTurtle() repeat 50: angle = randint(0, 360) setHeading(angle) forward(30) |
REMEMBER... |
from random import randint mports the randint() function from the random module. randint(a, b) generates a random integer number between a and b, where a is the smallest and b is the largest number. |
TO SOLVE BY YOURSELF |
1. |
|
|||||
2. |
|
|