Kodeclik Blog
Printing patterns is a great way to practice loops and string manipulation in Python. In this post, we’ll explore different methods to create a right triangle pattern using Python, so you can choose the one that works best for you.
Here are different ways to print a right-angled triangle pattern each parameterized by n, the size of the triangle. In other words, we use the value of n and use it to determine the number of rows of the right-angled triangle.
Method 1: Use Nested Loops
In this approach, we use a for loop to iterate through the rows of the triangle.
def triangle_nested_loops(n):
for i in range(1, n + 1):
print('*' * i)
triangle_nested_loops(6)
For each row, we print a string of asterisks (*) that matches the row number. The * character is repeated using Python's string multiplication feature, ensuring that each line has the correct number of asterisks. Since the loop runs from 1 to n, where n is the triangle's height, the output forms a right-angled triangle of size n. This method is simple, efficient, and easy to understand.
The output will be:
*
**
***
****
*****
******
What if you like a right triangle pattern with the vertical side on the right?
To print the right-angled triangle so that the vertical side is on the right, we need to right-align the * characters. This can be done by using rjust(n), which right-justifies the stars within a string of width n.
Here is a suitable change to the program:
def triangle_right_aligned(n):
for i in range(1, n + 1):
print(('*' * i).rjust(n))
triangle_right_aligned(6)
The output will now be:
*
**
***
****
*****
******
For fun, here is how you would print both left and right triangle patterns together:
def print_double_triangles(n):
for i in range(1, n + 1):
left_triangle = '*' * i
right_triangle = ('*' * i).rjust(n)
print(left_triangle.ljust(n) + ' ' + right_triangle) # Aligning both properly
print_double_triangles(6)
The output will be:
* *
** **
*** ***
**** ****
***** *****
****** ******
Henceforth, we will use the original format but you should realize that you can always change the program to make the right triangle aligned right.
Method 2: Use a Single Loop and join()
This method builds the triangle using list comprehension inside a loop.
def triangle_join(n):
for i in range(1, n + 1):
print(''.join(['*' for _ in range(i)]))
triangle_join(8)
For each row, we create a list of i asterisks and use ''.join() to convert the list into a string. The advantage of this approach is that it makes use of list comprehension, which is a Pythonic way of handling iterations in a compact manner. Although it does not offer significant performance benefits over string multiplication, it demonstrates an alternative way of generating patterns dynamically.
The output is:
*
**
***
****
*****
******
*******
********
Method 3: Use Recursion
In this recursive approach, we define a function that prints a row and then calls itself with an incremented row number until it reaches n.
def triangle_recursive(n, i=1):
if i > n:
return
print('*' * i)
triangle_recursive(n, i + 1)
triangle_recursive(5)
The base case occurs when the current row number (i) exceeds n, at which point the function stops calling itself. This method avoids explicit looping but relies on function calls, which may lead to higher memory usage due to the recursive stack. While recursion is not the most efficient method for this task, it is useful for understanding how problems can be broken down into smaller instances of themselves.
The output is:
*
**
***
****
*****
Method 4: Use map() and range()
This method leverages the map() function to apply a lambda function to each number in the range from 1 to n.
def triangle_map(n):
list(map(lambda i: print('*' * i), range(1, n + 1)))
triangle_map(3)
The lambda function prints a row of asterisks for each value of i. Since map() is typically used for transforming sequences, using it for printing is unconventional but still effective. The benefit of this approach is its conciseness, as it eliminates the need for an explicit loop while still iterating over the required range of values. However, it is slightly harder to read compared to the traditional loop-based approach.
The output is:
*
**
***
By now, you should have a good grasp of different ways to print right-angled triangle patterns in Python. Whether you use loops, string manipulation, or recursion, each method gives you insight into how Python handles strings and iteration. Keep experimenting with different patterns, try modifying the code, and challenge yourself to create new designs. Happy coding! 🚀
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.