Python Program to print the pattern G
In this tutorial, we will learn how to print the pattern G with stars and white spaces. We'll create a program to display the pattern G over n lines or rows. We will create the pattern G using the simple logic of iteration over lines in this program.
Let us look at the input-output for a better understanding:
The above image is the output of the program, we are going to cover below. In this, the user is first prompted to enter the size you want to print G and the output pattern is of G as shown above.
As mentioned above in the input-output part, let us now have a look at how this program is going to give us the desirable output:
- In this program, we are going to print the pattern using " * " and white spaces.
- We're going to do the operations column by column. So, we create the first if condition for the first line of stars, where the row positions 0 and (n-1) will not get the stars, but all other rows from 1 to (n-1) will get the stars.
- Similarly, we want stars in the second, third, and fourth columns at the row = 0 and row = 1 positions (n-1). The remaining stages are self-explanatory and may be deduced from the diagram's row and column positions.
- The resulting is the pattern which we want i.e., G.
As of now, we have a rough understanding to print the pattern, below is the implementation of the program where we will see the algorithm followed by the code:
The algorithm to print pattern is mentioned below:
- Create a function pattern()
- We only perform two things here: print star(*) and print space( ).
- We are simply writing the conditions to make the pattern of *'s and display the pattern ‘G'.
- Make two loops: one for rows and one for columns.
- The outer loop is for rows
- The Inner loop is for columns
- Now, Print the first row and Print the last row
- Print the first column and print the last column
- Print the middle column
- The result printed will be G
for row in range(n):
for col in range(n):
if ((row == 0 and (col != 0 and col != n-1)) or
(row == n - 1 and (col != 0 and col != n-1)) or
((col == 0 and (row != 0 and row != n-1)) or
(col == n-1 and row != n-1 and row >= (n/2)-1)) or
(row == (n/2)-1 and ((n/2)-1 <= col < n-1))
print("*", end=" ")
print(" ", end=" ")
# driver code
n = int(input("Enter the size you want: \t"))
if size < 8:
print("Enter a size greater than 8")
In this tutorial, we have print the letter 'G' with help of stars and spaces with simple iteration and loops. We can also print this pattern with any symbol you want. I hope, you will follow up on this and print the pattern with your favorite symbols just remove the star and add the symbol you want and enjoy printing "G" in python programming.