Explore

Python Programs

Draw Square In Python Without Turtle

Draw Square In Python Without Turtle

Today in this article we will see how to draw a square in python without turtle library which is a GUI library in python which can be used to draw things so we will not use it to draw a square in python.

To draw a square in python I will show you two methods one by using the pygame library which is a game development library in python and another using for loop.

Draw A Square In Python Using Pygame


import pygame

# Initialize Pygame
pygame.init()

# Setting window and color
size= 400,400
white_color = 255, 255, 255
screen = pygame.display.set_mode(size)
screen.fill(white_color)

# Set the position and size of the square
rect = pygame.Rect(100, 100,200,200)

# Draw the square
pygame.draw.rect(screen, (0, 0, 0), rect, 1)

pygame.display.flip()

# Keep the window open until it is closed
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()


Above is the python code to draw a square in python pygame module you can run this code on your machine or using an online python compiler and see the output.

Before running you need to install pygame module in your system since we are using it to draw a square you can install it by using below command.


pip install pygame

Above command will install the pygame module and now you can run it and after running you will see a square drawn like below.

Square Drawing In Python

As you can see after running we successfully drawn a square in python without using turtle module. Now let’s see how to draw using for loop.

Draw A Square In Python Using For Loop


# Set the side length of the square
side = 5

# Loop through each row
for i in range(side):
    # Loop through each column in the row
    for j in range(side):
        # If we are on the first or last row, or the first or last column, print an asterisk
        if i == 0 or i == side - 1 or j == 0 or j == side - 1:
            print("*", end=" ")
        # Otherwise, print a space
        else:
            print(" ", end=" ")
    # Move to the next row
    print()

Above is the code to draw a square in python by using for loop. You can run this code on your system or use this online python compiler to run now.

After running this program you will see a square pattern drawn like below.


* * * * *
*       *
*       *
*       *
* * * * *

As you can see we successfully drawn a square in python using a loop. Want to draw a circle in python without using turtle refer here: Draw circle in python without turtle.

I hope you found this tutorial helpful and useful. Do share it with someone who might need this. If you want updates of our blog then join our telegram channel.

Thanks for reading, Have a nice day 🙂