2 ways to Draw a square with Python

dibujar con python y turtle un cuadrado draw a square with python
k

11/03/2023

DRAW A SQUARE WITH PYTHON AND TURTLE LIBRARY

We will draw a Square with Python and the Turtle library using the code of various shapes. The Turtle library is based on the LOGO language, used in the introduction to programming for children. This module allows us to draw any polygon with Python in a very interactive and didactic way.

First of all, we will use simpler code to advance in the level of complexity of the code.

DRAW A SQUARE WITH PYTHON

Our first step will be to import the turtle module, with the keyword ‘import‘ reserved. Once we have imported the turtle module, we will have access to the functions and objects that it contains.

Next, we access the turtle.Turtle() constructor which we assign to a variable called t.

Py

#import turtle library
import turtle
#create the turtle object
t = turtle.Turtle()

Once we execute the previous code, an arrowhead appears on the screen as seen in the image below, which is nothing more than the t object in its initial state.

simbolo inicio turtle

The first step in drawing the square with Python is to move the object t. In this example, we will move it 150 pixels to the right. Later we rotate 90 degrees to orient the object in another direction.

Py

#move right 150 pixels
t.forward(150)
#turn 90 degrees to the left
t.left(90)

After executing the code it shows us the following

desplazamiento hacia delante
giro a la izquierda

So if we repeat the previous commands another three times, it will give us a square as a result.

Py

#move right 150 pixels
t.forward(150)
#turn 90 degrees to the left
t.left(90)
#move right 150 pixels
t.forward(150)
#turn 90 degrees to the left
t.left(90)
#move right 150 pixels
t.forward(150)
#turn 90 degrees to the left
t.left(90)
cuadrado completo

DRAW A SQUARE WITH A FOR LOOP

Previously we were able to draw a square with Python, simply with a command repetition. The drawback of this method is that it is a bit tedious to use more code than necessary.

By using a ” for ” loop, with Python, we can achieve the same result but without as much code.

Previously we will clear the previous square from the screen and also return the initial position to t. For that, we will use t.clear()

Py

#clear the screen and reset t
t.clear()
#move 150 pixels to the right and turn 90 degrees
for i in range(4):
  t.forward(150)
  t.left(90)

This code will return the figure of the complete square

DRAW A SQUARE WITH A FUNCTION

We can also draw a square with python a more complete code by the use of a function. Again, we use the clear() function to clear the screen.

Py

#clear the screen and reset t
t.clear()
#move 150 pixels to the right and turn 90 degrees
function cuadrado(t,d,reseteo):
  #definimos la función resetear
  if reseteo == True:
    resetear()
  #dibujar el cuadrado
  for i in range(4):
    t.forward(d)
    t.left(90)
function resetear():
  turtle.resetscreen()

#call the function Cuadrado
cuadrado(t,150,True)

This code will also return the figure of the complete square.

The square function receives 3 parameters: t, d, and reset.

The t refers to the turtle object we talked about earlier.

The d is the distance in pixels from each side of the square that we want to draw. In this case, we have called the function with a value of 150 but it could be any other.

And finally reset tells us if we want to reset the screen before drawing a new square. If instead of True we write False, the reset() function is not executed, so it will draw a new figure without the canvas necessarily being empty or not. Below is an example of False as a parameter.

cuadrados superpuestos

Creatuwebpymes is a web design company based in Lanzarote – Canary Islands. We ❤️ programming in Python, hence the reason for this post.

This post is an exercise that Python students usually come across in their initial projects. If you wish to learn more about this language, here are some ebooks to learn Python code.

 

creatuwebpymes quien somos

Francisco Brito Diaz

CEO of Creatuwebpymes, is a web design company and marketing digital based in Lanzarote – Canary Islands

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos y para fines de afiliación y para mostrarte publicidad relacionada con sus preferencias en base a un perfil elaborado a partir de tus hábitos de navegación. Contiene enlaces a sitios web de terceros con políticas de privacidad ajenas que podrás aceptar o no cuando accedas a ellos. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos.
Privacidad