Python Program to print the pattern 'G'

When it is required to print the pattern of the letter 'G' using '*', a method can be defined, and nested loops can be used to iterate through the numbers and print '*' to form a 'G' pattern.

Below is a demonstration of the same −

Example

def display_pattern(my_line):
    my_pattern = ""
    for i in range(0, my_line):
        for j in range(0, my_line):
            if ((j == 1 and i != 0 and i != my_line-1) or 
                ((i == 0 or i == my_line-1) and j > 1 and j < my_line-2) or 
                (i == ((my_line-1)//2) and j > my_line-5 and j < my_line-1) or 
                (j == my_line-2 and i != 0 and i != my_line-1 and i >= ((my_line-1)//2))):
                my_pattern = my_pattern + "*"
            else:
                my_pattern = my_pattern + " "
        my_pattern = my_pattern + "\n"
    return my_pattern

num_line = 8
print("The pattern G has been shown below:")
print(display_pattern(num_line))

Output

The pattern G has been shown below:
  ****  
 *      
 *      
 *      
 *  **  
 *   *  
 *   *  
  ****  

How It Works

The pattern consists of several parts that form the letter 'G':

  • Left vertical line: Column index j == 1 (except first and last rows)

  • Top and bottom horizontal lines: First row (i == 0) and last row (i == my_line-1)

  • Middle horizontal line: At row i == (my_line-1)//2 for the inner part of 'G'

  • Right vertical line: Column j == my_line-2 for the bottom half of 'G'

Customizable Pattern Size

def display_pattern(my_line):
    my_pattern = ""
    for i in range(0, my_line):
        for j in range(0, my_line):
            if ((j == 1 and i != 0 and i != my_line-1) or 
                ((i == 0 or i == my_line-1) and j > 1 and j < my_line-2) or 
                (i == ((my_line-1)//2) and j > my_line-5 and j < my_line-1) or 
                (j == my_line-2 and i != 0 and i != my_line-1 and i >= ((my_line-1)//2))):
                my_pattern = my_pattern + "*"
            else:
                my_pattern = my_pattern + " "
        my_pattern = my_pattern + "\n"
    return my_pattern

# Try different sizes
for size in [6, 10]:
    print(f"Pattern G with size {size}:")
    print(display_pattern(size))

Conclusion

This program uses nested loops with conditional logic to print the letter 'G' pattern. The conditions check specific positions to place '*' characters forming the horizontal and vertical lines that make up the letter 'G'.

Updated on: 2026-03-25T18:48:53+05:30

642 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements