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 loop 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 :
****
*
*
*
* *
* *
* *
****

Explanation

  • A method named ‘display_pattern’ is defined that takes the line as parameter.

  • Nested loop is used to iterate through the numbers,

  • The ‘*’ is printed whenever a condition is met.

  • When the base condition is reached, the output is displayed on the console.

  • The control comes out of the loop.

Updated on: 15-Apr-2021

409 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements