Print circle pattern in Python

In this tutorial, we are going to learn how to print a circle pattern in Python.

For printing circle pattern we use two nested for loops.

we will also see an example code to understand it.

Steps for printing circle pattern in Python

In this program, we are using  ‘*’ to draw the circle pattern.

we will see the steps with example code to draw circle pattern.

STEP 1:-

Initialize the number of rows and columns.

for example:-

rows =7
columns=5

 

STEP 2:-

Nest two for loops. outer for loop will iterate rows and inner for loop will iterate columns.

Syntax of nesting two for loops

here i and j are iterators.

for i in range(0,row):
    for j in range(0,col):

STEP 3:-

Now we will use proper condition to print circle

  • condition 1:- to print ‘*’at first and last column but not at first and last row,
  • condition2:-to print ‘*’at first and last rows but not at first and last columns.
  • if the above two conditions are not satisfied then print space (‘ ‘).

code to implement all conditions as follows:-

if((j == 0 or j == columns-1) and (i!=0 and i!=rows-1)) :
     print('*',end='')
 elif( ((i==0 or i==row-1) and (j>0 and j<columns-1))):
     print('*',end='')
 else:
     print(end=' ')

EXAMPLE

Example to print circle pattern using ‘*’ is as follows

row =6
col=4

for i in range(0,row):
    for j in range(0,col):
        if((j == 0 or j == col-1) and (i!=0 and i!=row-1)) :
            print('*',end='')   #end='' so that print statement should not change the line.
        elif( ((i==0 or i==row-1) and (j>0 and j<col-1))):
            print('*',end='')
        else:
            print(end=' ')  #to print the space.

    print()  #to change the line after iteration of inner loop.

output:-

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

Also read:

Python Program To Print Hollow Box Pattern

Leave a Reply