# Patterns (Solution)

I hope you have solved the problems which I gave you in my last python blog. So today we will see the solutions for that problem. I know, as I said today we are gonna see number patterns but as I was not able to explain you the reverse loop concept, today we will complete it and will start number patterns in next blog. Following are the patterns for which you had to write the code:

We can notice in the first and second patterns that we have to just print the stars according to a rule that stars depend upon the no of lines, first line means just one star, second means 2 and so on. In the second pattern the reverse process is happening, where we are starting with the maximum number till we reach one star. Let us see the code for the first pattern:

It was a easy one, hope you all would have done it. Now comes the tricky part, as in the second pattern we have to run the loop in reverse order but I never explained you how to do it. Those who had the curiosity may would have referred the net for assistance, while other would have used some other logic. So now let me show you how to run the loop in reverse order. The syntax of for loop in python is:

for variable in range(starting,ending,incrementation/decrementation):

Usually when we are using “for” loop we are not writing incrementation/decrementation as by default it is +1. So when we write:

### for i in range(0,n):

Compiler actually compiles it as:

### for i in range(0,n,1):

It means after each execution increase the value of i by 1. Hence when we have to run the loop in reverse we have to write explicitly ‘-1’, which will state that decrease the value of i after each execution. Hence now we can write the code for II pattern as follow:

III and IV are bit complex as there we have to print “spaces” along with the stars. I will illustrate you the logic and code for III pattern, you have to find the solution for IV. In III pattern, in the first line we have to print 4 spaces and 1 star, then 3 spaces and 2 stars and so on. We will use 3 loops here, one will be for the counter value, one for spaces and one for the stars.

#### for i in range(0,k): #for number of times loop should run for j in range(k-i,1,-1): #spaces print(“ “,end=””) for z in range(0,i+1): #stars print(“*”,end=””)

So today we learnt an extra thing, can you guess what? Yes!! Now we know how to give comments in python. We can use “#” to give comments in python. Now we have solved 3 patterns, the 4th is left for you. We will solve some tricky number patterns in the next blog. Till then keep coding…

Like what you read? Give Ashish Sharma a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.