Advertisement
Guest User

Area and perimeter of rectangle

a guest
Dec 15th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.36 KB | None | 0 0
  1. #imports modules from libraries
  2. from turtle import *
  3. from random import randint
  4. import random    
  5.  
  6. bob = Turtle()  #Creates a turtle
  7. col = ["Red", "Green", "Blue", "Pink"]  #Creates a list and assigns values
  8.  
  9. def area(l, h):   #defines a function which calculates the area of a triangle
  10.   a = l * h       #multiples the length by height and stores in a variable
  11.   return a        #returns the area
  12.  
  13. def perimeter(l, h):
  14.   p = (l + h)* 2
  15.   return p
  16.  
  17. def randomplace():    #defines a function called randomplace
  18.   x = randint(-200, 200)   #creates a variable and assigns a random integer
  19.   y = randint(-200, 200)   #creates a variable and assigns a random integer
  20.   bob.goto(x,y)
  21.  
  22. def center_rectangle(l, h):     #defines a function that returns the
  23.   bob.right(90)            
  24.   bob.forward(l/2)              #moves the turtle forward half the length of the rectangle
  25.   bob.right(90)
  26.   bob.forward(h/2)              #moved the turtle forward half the width of the rectangle
  27.  
  28.  
  29.  
  30. def draw_rect(l, h, cols):  #defines a function and passes in three parameters
  31.   hideturtle()              #hides the turtle from view
  32.   bob.penup()                   #the pen is not currently drawing
  33.   randomplace()             #calls the randomplace function to select random coordinates
  34.   bob.pendown()
  35.   bob.fillcolor(cols)        #selects random colour from cols list
  36.   bob.begin_fill()           #fills in shape with selected colour
  37.   bob.forward(l)             #Moves the turtle forward a random number which has been passed in
  38.   bob.right(90)              #turns the turtle a 90 degrees angle is it is pointing the correct way
  39.   bob.forward(h)             #moves the turtle forward a random number which has been passed in
  40.   bob.right(90)
  41.   bob.forward(l)
  42.   bob.right(90)
  43.   bob.forward(h)
  44.   bob.end_fill()              #end the fill colour
  45.   bob.penup()
  46.   center_rectangle(l, h)      #calls a fuction which will return the turtle to the center of the rectangle
  47.   bob.pendown()
  48.   bob.color("black")          #wrties text in black
  49.   bob.write("Area: " + str(area(l, h)) + "\nPerimeter:" + str(perimeter(l, h)))  #prints the area and perimeter
  50.   bob.penup()
  51.  
  52. for i in range(5):          #for loop which repeats 10 times
  53.   draw_rect(random.randint(-100,100), random.randint(-100, 100), random.choice(col))
  54. #calls the draw_rect function and passess in three parameters
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement