Hello friends, It’s always a pleasure to work on the basics if you are learning any programming language. And if you are attending a software interview you may be asked to draw the common shapes like triangle, inverted triangle in python.
Draw Triangle in Python
I found Python programming language to be the most easier one to draw these shapes. Below is the code example.
In just four lines of code you can draw a triangle in Python. Out of these four line two are setting up of variables, practically it is only two lines of code.
Initially I am creating two variable that contains the height of triangle i.e rows and the character to draw.
Than comes the core logic. I am just print the blank space. The blank space is rowNumber subtracted from total number of rows times ” “.
For example, for first row I need 10 blank spaces before I print star, it will be (10 – 0) * ” “. The multiply operator helps to print the character number of times.
Than I am printing the number of characters, for first row it will be single , for second row it will be three and so on.
Draw inverted triangle in Python
The logic to create an inverted triangle derived from the above code. We have to just start the loop from the end. Below is the code
On line 26 you can see, I have reversed the loop. The loop will start from 10 and go one by one in back word direction using the range(10, 0 , -1).
Draw complex Shape in Python
Once we are able to draw some basic shapes, we can draw even more complex shapes. Below is the examples of one of the complex shape I will discuss.
The Python code to write this shape is below.
def DrawShape(): ToPrint = "*" Length = 10 for char in range(1,Length + 1): BlankSpaceLength = (Length * 2) - (char * 2) Space = " " * BlankSpaceLength print(ToPrint * char + Space + ToPrint * char ) for char in range(Length - 1, 0, -1): BlankSpaceLength = (Length * 2) - (char * 2) Space = " " * BlankSpaceLength print(ToPrint * char + Space + ToPrint * char )
In this article I have written python code to write some of the shapes like triangle, inverted triangle and other complex shapes.
Leave a Reply