Python Practice › Loop Programs › Program 2

Star pattern that grows then shrinks

EasyLoop Programs · 2 of 90

Write a Python program to print a star pattern that grows from 1 to 5 stars and shrinks back to 1, using nested loops.

Advertisement
Output
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

Approach

  1. First loop: rows 1 to 5. Second loop: rows 4 down to 1.
  2. An inner loop prints the stars of each row.

Solution

Python
n = 5for i in range(1, n + 1):    for _ in range(i):        print("*", end=" ")    print()for i in range(n - 1, 0, -1):    for _ in range(i):        print("*", end=" ")    print()
Output
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

Line by line

Lines 2-5

Row i prints i stars; end=" " keeps them on one line and print() ends the row.

Line 6

range(n - 1, 0, -1) counts 4, 3, 2, 1 for the shrinking half.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs