• Homework
  • Thirds
  • Upper Thirds
  • Fourth
  • Divisions
    • ICT
    • Computer Science
  • Fifth
  • Lower Sixth
  • Upper Sixth
    • Upper Sixth Theory
  • Blog
  • Careers
  • Unity
  • Networking

Random numbers in Python

Python has a special module that will generate random numbers.  To use it you must import it first
import turtle,random
It's the same as importing the Turtle module.  We've now got two import modules so we put them both on the first line and separate them with commas.

Generating a random number

The most useful command is randrange(start, finish)
Here's a program fragment with a function that will get a random colour.
Note that random.randrange(7) will give numbers between 0 and 6 - it will never produce a 7
import turtle,random

colors = ("red","green","blue","yellow","black","purple","cyan","magenta")

def randomcolor():
    randomnumber = random.randrange(7)
    turtle.color(colors[randomnumber])

Challenge 1

Here's the main program.  You can copy this
while True:
    turtle.speed(0)
    turtle.penup()
    randomposition()
    randomrotation()
    randomcolor()
    square(random.randrange(20,80))

turtle.exitonclick()


Your challenge is to make the functions that will make it work and produce the output on the right

More challenges

Picture
Powered by Create your own unique website with customizable templates.