Python Program to Print an Hourglass Pattern
Beginner · Patterns
An hourglass pattern looks like a sand timer: an upside-down pyramid on top of a normal pyramid, meeting at a single star in the middle. With 5 rows in each half, the rows have 9, 7, 5, 3 and 1 stars, then 3, 5, 7 and 9 again.
Program
*********
*******
*****
***
*
***
*****
*******
*********How it works
- Both halves use the pyramid rule: row
ihasrows - ispaces and then2 * i - 1stars. - The top half counts
idown from 5 to 1, which draws an inverted pyramid ending in the single star at the waist. - The bottom half counts
iup from 2 to 5, starting at 2 rather than 1 so the middle star is not printed twice. " " * nand"*" * nbuild each part of the row by repeating a character.
Other ways to write it
Hourglass with spaces between the stars
* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *With "* " repeated i times, the rows have 5, 4, 3, 2 and 1 stars and then grow again, and one space of indent per row keeps them centred.
One loop using abs()
*********
*******
*****
***
*
***
*****
*******
*********abs(k) + 1 is large at both ends of the loop and 1 in the middle, which is exactly the shape of an hourglass.
Try it yourself
Make the hourglass hollow, so each row prints only its first and last star.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises