When we are writing a lot of code that is very similar, and we can simplify this by using subroutines. We may use subroutines to optimise the repetition when the repeated is not contigious.
We start all subroutines off with def
followed by a name. Ensure they end with a set of brackets and a colon. All the code indented inside of the subroutine is what is run when it is called. Whenever we call the name of the subroutine with a set of brackets, it runs the indented code. We can call the subroutine as many times as we like, and it runs the same way every time. Remember, it does not run the code until it is called.
import turtle
def draw_square():
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
draw_square()
turtle.penup()
turtle.right(90)
turtle.forward(200)
turtle.pendown()
draw_square()
turtle.penup()
turtle.forward(100)
turtle.pendown()
draw_square()
turtle.penup()
turtle.forward(100)
turtle.pendown()
draw_square()
The above code defines how the program should draw a square. The square is not drawn until the user writes draw_square().