Printing pattern of triangles made with one character using the fundamental concepts of PYTHON like print function and for loop only.
Hey CodeSpeeder!
Everyone knows about functions like print() and iterative methods like for loop. Very basic, right? Yet enough to build beautiful and creative patterns to display! Explore this article further to code various triangles displayed using characters.
*
* *
* * *
* * * *
* * * * *
def right_triangle_left(ch, n): for i in range(n): print((ch+" ")*(i+1)) right_triangle_left('*', 5)
* * * * *
* * * *
* * *
* *
*
def right_triangle_left_inverted(ch, n): for i in range(n): print((ch+" ")*(n-i)) right_triangle_left_inverted('*', 5)
0
0 0
0 0 0
0 0 0 0
0 0 0 0 0
def right_triangle_right(ch, n): for i in range(n): row=" "*(2*(n-i-1))+(ch+" ")*(i+1) print(row) right_triangle_right('0', 5)
0 0 0 0 0
0 0 0 0
0 0 0
0 0
0
def right_triangle_right_inverted(ch, n): for i in range(n, 0, -1): row=" "*(2*(n-i))+(ch+" ")*(i) print(row) right_triangle_right_inverted('0', 5)
^
^ ^
^ ^ ^
^ ^ ^ ^
^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^
def triangle_middle(ch, n): for i in range(n): row=" "*(n-i-1)+(ch+" ")*(i+1) print(row) triangle_middle('^', 6)
^ ^ ^ ^ ^ ^
^ ^ ^ ^ ^
^ ^ ^ ^
^ ^ ^
^ ^
^
def triangle_middle_inverted(ch, n): for i in range(n, 0, -1): row=" "*(n-i)+(ch+" ")*(i) print(row) triangle_middle_inverted('^', 6)
@
@ @ @
@ @ @ @ @
@ @ @ @ @ @ @
@ @ @ @ @ @ @ @ @
def triangle_big_middle_inverted(ch, n): for i in range(1, 2*n, 2): row= (" ")*(2*n-i) + (ch+" ")*(i) print(row) triangle_big_middle_inverted('@', 5)
@ @ @ @ @ @ @ @ @
@ @ @ @ @ @ @
@ @ @ @ @
@ @ @
@
def triangle_big_middle_inverted(ch, n): for i in range(2*n-1, 0, -2): row= (" ")*(2*n-i) + (ch+" ")*i print(row) triangle_big_middle_inverted('@', 5)
>
> >
> > >
> > > >
> > >
> >
>
def triangle_flag_towards_right(ch, n): n=n//2 right_triangle_left(ch, n+1) right_triangle_left_inverted(ch, n) triangle_flag_towards_right('>', 7)
<
< <
< < <
< < < <
< < <
< <
<
def triangle_flag_towards_left(ch, n): n=n//2 right_triangle_right(ch, n+1) def right_triangle_right_inverted(ch, n): for i in range(n, 0, -1): row=" "*(2*(n-i+1))+(ch+" ")*(i) print(row) right_triangle_right_inverted(ch, n) triangle_flag_towards_left('<', 7)
I have tried to display the most common types of triangles that are constructed using only one character.
Your looping fundamentals will surely improve after practicing these patterns.
Also, create some more amazing patterns of your own!
Submitted by Kalki Pareshkumar Bhavsar (KalkiBhavsar)
Download packets of source code on Coders Packet
Comments