Square pattern in Python

Lareina 143 Published: 12/20/2024

Square pattern in Python

I'd be happy to help you with that! Here's a simple script in Python to generate a square pattern:

import turtle

def draw_square(t, size):

for _ in range(4):

t.forward(size)

t.right(90)

window = turtle.Screen()

window.bgcolor("white")

my_turtle = turtle.Turtle()

my_turtle.shape("turtle")

my_turtle.color("blue", "green")

for _ in range(5): # Draw 5 squares

draw_square(my_turtle, 50) # Size of the square

my_turtle.penup() # Lift the pen

my_turtle.forward(60) # Move to next position

my_turtle.pendown() # Drop the pen

window.mainloop()

Let me explain what this script does:

Import turtle module which is used for creating simple graphics in Python. Define a function draw_square(t, size) that uses turtle graphics to draw a square of given size. Create a turtle object and set its shape, color, and background color. Use the draw_square() function to draw 5 squares of different sizes (in this case, all of them are 50 units in size). Move the turtle to next position after drawing each square. The script then enters a loop until it draws all the squares. Finally, it runs the main event loop (window.mainloop()) for turtle graphics.

So when you run this script, you'll see 5 blue and green squares drawn in your screen!

How to print right angled triangle in Python using while loop?

I'm happy to help you with that!

Printing a right-angled triangle in Python can be achieved by utilizing a while loop. The idea is to keep track of the number of rows and columns, and adjust the spacing accordingly.

Here's an example code snippet:

rows = 5  # You can change this value to print a different-sized triangle

i = 1 # Initialize the row counter

while i <= rows:

print(' ' * (rows - i), end='') # Print leading spaces

j = 1 # Initialize the column counter

while j <= i:

print('*', end=' ') # Print asterisks

j += 1

print() # Move to a new line

i += 1

Let's break down what this code does:

We set rows to a desired value (e.g., 5). This will determine the height of the triangle. The outer while loop iterates from 1 to rows. In each iteration, we print leading spaces using ' ' * (rows - i). For each row, we have an inner while loop that prints asterisks (*) up to a maximum number of columns equal to the current row value (i). After printing the asterisks, we move to a new line with print().

Here's the output for the code above:

    *




You can adjust the rows value to create different-sized triangles. For example, if you set rows = 3, the output will be:

  *


I hope this helps you understand how to print a right-angled triangle in Python using a while loop!