Python Practice › Loop Programs › Program 10

Letter O pattern

MediumLoop Programs · 10 of 90

Write a Python program to print the letter ‘O’ with stars.

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

Approach

  1. The top and bottom rows print stars in the middle columns.
  2. The other rows print a star only in the first and last columns.

Solution

Python
rows, cols = 7, 5for r in range(rows):    line = ""    for c in range(cols):        top_or_bottom = (r == 0 or r == rows - 1) and 0 < c < cols - 1        side = 0 < r < rows - 1 and (c == 0 or c == cols - 1)        line += "*" if top_or_bottom or side else " "    print(line)
Output
 *** 
*   *
*   *
*   *
*   *
*   *
 *** 

Line by line

Line 5

The first and last rows get stars only between the corners, which rounds the shape.

Line 6

The middle rows get stars only on the left and right edges.

Line 7

Each position adds a star or a space.

Learn the concept

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

More loop programs

← All 90 Loop Programs

Leave a Comment