Print Pascal’s triangle in Python
In this tutorial, we will learn how to print Pascal’s triangle in Python.
Pascal Triangle in Python- “Algorithm”
Now let us discuss the algorithm for printing Pascal’s triangle in Python.
Steps involved:
1. Two nested loops must be used to print the pattern in 2-D format.
2. The number of elements in each row is equal to the number of rows.
3. The 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): C = 1 # Initializing the value of C for the first element in the line for i in range(1, line + 1): print(C, end=" ") # Printing the value of C followed by a space C = C * (line - i) // i # Calculating the next value of C print() # Moving to the next line n = 5 printPascal(n)
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 the outer loop. The variable C contains the series of numbers to be printed. The outer loop contains escape sequence “\n” which makes it to the next line after each iteration.
Output:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Also, check out these for a wider grasping of knowledge:
Were glad to become visitor on this pure site, regards in this rare info!