ByteBoard Notes Notes

Generate star, number and letter patterns using nested loops

Computer Science XI · Experiment 08 of 27 · Python

★ CBSE suggested11-CSPython programs
Expt. No.08
Page No.16

Patterns with nested loops

Aim

To write a Python program that prints three patterns (a star triangle, a falling number triangle and a letter triangle) using nested loops.

Concepts used

Algorithm

  1. Input the number of rows n.
  2. Pattern 1: for row i from 1 to n, print i stars.
  3. Pattern 2: for row i from n down to 1, print the numbers 1 to i.
  4. Pattern 3: for row i from 0 to n-1, print the first i+1 letters of the alphabet.

Program

# Three patterns using nested loops n = int(input("Enter the number of rows: ")) print("Pattern 1")for i in range(1, n + 1):    for j in range(i):        print("*", end="")    print() print("Pattern 2")for i in range(n, 0, -1):    for j in range(1, i + 1):        print(j, end="")    print() print("Pattern 3")letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"for i in range(n):    for j in range(i + 1):        print(letters[j], end="")    print()

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python patterns_nested_loops.py
Enter the number of rows: 5 Pattern 1 * ** *** **** ***** Pattern 2 12345 1234 123 12 1 Pattern 3 A AB ABC ABCD ABCDE

✓ Printed by running this program, not typed by hand.

Result

With 5 rows the program printed the star triangle (1 to 5 stars), the number triangle from 12345 down to 1, and the letter triangle from A to ABCDE.

Viva voce: what the examiner may ask

01What does end="" do in print()?

It stops print() from moving to a new line, so the next value is printed on the same line.

02Why is there an empty print() after the inner loop?

It ends the current row by moving to the next line.

03What does range(n, 0, -1) produce for n = 5?

5, 4, 3, 2, 1. The third argument is the step, and the stop value 0 is not included.

04How is the letter picked in Pattern 3?

By indexing the string: letters[0] is "A", letters[1] is "B", and so on.

Variations for the lab test

  1. Print the star triangle upside down.
  2. Print the pattern 1, 22, 333, 4444, 55555.
  3. Print a right-aligned star triangle using spaces.
! Common mistake Forgetting the empty print() after the inner loop prints every row on one long line.
Back to the 11-CS index