Today as I told we are gonna do something interesting, something which many people are afraid of and they think it is very hard. We will be working with patterns today and I will show you how to do some of the basic patterns. The concept of looping which is used here is same as that of C/C++, so if you know how to draw patterns in C, then it will be a cakewalk for you guys. But there is a slight difference in the code in python. Let me show you what I did first when I started patterns. I started with the simplest of the pattern which is shown below:

So in this pattern we have to print the number of stars depending upon our input. If our input is 5, as shown, then we should print stars in 5 rows and 5 columns. So whatever our input is ’N’, we have to print a NxN pattern. I wrote my first code for pattern in python in the same way as we will write in C.

So do you think this code will generate the output which is required??? Actually I thought so, so when I executed the above program I got the following result:

So I came to know that my all the stars are printing on the next line and then, when a newline escape sequence is encountered a new blank line is produced. So where do you think is the error? Actually we will not be able to see our mistake in the above code as it is not visible. Then if it is not visible, then how are we gonna correct it will be our next question. So the most common and important thing which we have to remember while drawing patterns in python is the role of “end”.

By default whenever we are writing our print statement, end is written in the background of our program and is assigned as ‘\n’. Hence after each and every print statement, our star goes to the next line. Below is the representation of the code of how you will see it and how compiler actually compiles it.

We are writing our print statement as:


How our compiler compiles it as:


We will not be able to see the “\n”, but our compiler will compile it as that is inbuilt. Hence in order to print our required no of stars in the same line, we will change the “\n” as “ ”. Hence for our case 5 stars will be printed in the same line and then “\n” will be executed which will take the control to next line. Then again for n=1 loop will run in the same manner until i=4.

Now after changing our code we are getting 5–5 stars in each row. But still there is a lot of gap between two rows, hence we can improve our code by using “\r”, which will reduce the distance between two rows.


Above as you can see our final code and our output. So this is the only thing which you have to take care in python, rest of the things as far as I know, are same as in C. So I’ll be showing some of the patterns below, please give it a try. If you can solve all, kudos to you, if not no problem, I am here. Atleast give it a try.


This was the basics, we will discuss patterns with numbers in the next blog. Till then keep coding…