Pascal Triangle in Python -A Problem on Looping Construct

In this tutorial ,we will learn about Pascal triangle in Python widely used in prediction of coefficients in binomial expansion.

Pascal Triangle in Python- “Algorithm”

Now let us discuss the algorithm of printing the pascal triangle in Python
After evaluating the above image of pascal triangle we deduce the following points to frame the code
1. Two nested loops must be used to print pattern in 2-D format.
2. Number of elements in each row is equal to the number of rows.
3. Number of spaces must be (total of rows – current row’s number) #in case we want to print the spaces as well to make it look more accurate and to the point.

Source Code – Pascal Triangle in Python

def printPascal(n):
    for line in range(1,n+1): 
        D = 1
        for i in range(1,line+1): 
            print D,
            D = D * (line - i) / i 
        print "\n"

n = 5

The above code declares a function named printPascal which contain two nested loop. The outer loop starts from 1 and terminates at n and the inner loop starts from 1 to till the counter of outer loop .The variable D contains the series of numbers to be printed .The outer loop contains escape sequence “\n” which make it to the next line after each iteration.



1 1 

1 2 1 

1 3 3 1 

1 4 6 4 1 

Also check out these for wider grasping of knowledge

One response to “Pascal Triangle in Python -A Problem on Looping Construct”

  1. OJ4u says:

    Were glad to become visitor on this pure site, regards in this rare info!

Leave a Reply