Register for 45 Day Coding Challenge by CodeStudio And Win Some Exciting Prizes

# Square Star Pattern in Python

Square star pattern in Python | In the below programs, we will develop a python program to print the square star patterns using the For Loop and While Loop.

## Python Program to Print Square Star Pattern using For Loop

In this program, we will use two For Loops (the first loop for the row and the second loop for the coloum) to print the square star pattern.

``````# Python program to print square star pattern

# take inputs
n = 5

# nested For Loop to print star
for i in range(n):
for j in range(n):
# printing stars
print("* ",end="")
print("\r")
``````

Output:-

`* * * * *`
`* * * * *`
`* * * * *`
`* * * * *`
`* * * * *`

In the previous program, inputs are hardcoded in the program but in this program, inputs will be provided by the user.

``````# Python program to print square star pattern

# take inputs
n = int(input('Enter the number of rows: '))

# nested For Loop to print star
for i in range(n):
for j in range(n):
# printing stars
print("* ",end="")
print("\r")``````

Output:-

Enter the number of rows: 4
`* * * *`
`* * * *`
`* * * *`
`* * * *`

We can also take the help of a user-defined function to print square star patterns in Python. A function is a block of code that performs a specific task.

``````# Python program to print square star pattern

def pattern(n):
for i in range(n):
for j in range(n):
# printing stars
print("* ",end="")
print("\r")

# take inputs
n = int(input('Enter the number of rows: '))

# calling function
pattern(n)
``````

## Square Star Pattern in Python

This python program also performs the same task but with different methods. In this program, we are using only one For Loop. This is the shortest method to print square star patterns in python.

``````# Python program to print square star pattern

def pattern(n):
for i in range(n):
# printing stars
print("* " * n)

# take inputs
n = int(input('Enter the number of rows: '))

# calling function
pattern(n)
``````

Output:-

Enter the number of rows: 3
`* * *`
`* * *`
`* * *`

In the previous program, we have used the For Loop to print square star patterns but in this program, we will use the While Loop.

``````# Python program to print square star pattern

def pattern(n):
i = 1
while i <= n :
j = 1
while j <= n:
# printing stars
print("*", end=" ")
j = j + 1
print()
i = i + 1

# take inputs
n = int(input('Enter the number of rows: '))

# calling function
pattern(n)
``````

Output:-

Enter the number of rows: 8
`* * * * * * * *`
`* * * * * * * *`
`* * * * * * * *`
`* * * * * * * *`
`* * * * * * * *`
`* * * * * * * *`
`* * * * * * * *`
`* * * * * * * *`

Shortest Method

``````# Python program to print square star pattern

def pattern(n):
i = 1
while i<=n:
# printing stars
print("* " * n)
i+=1

# take inputs
n = int(input('Enter the number of rows: '))

# calling function
pattern(n)
``````

Also See:- Pattern Programs in C