Program to create one triangle stair by using stars in Python

Suppose we have a number n, we have to create a string representing stairs with n steps. Each line in the string is separated by a newline separator, forming a triangle pattern with stars.

So, if the input is like n = 5, then the output will be ?

    *
   **
  ***
 ****
*****

Algorithm

To solve this, we will follow these steps ?

  • Initialize an empty string
  • For each step from 0 to n-1:
    • Add (n-i-1) number of spaces for right alignment
    • Add (i+1) number of stars for the current step
    • Add a newline character if not the last step
  • Return the final string

Example

class Solution:
    def solve(self, n):
        s = ""
        for i in range(n):
            s += " " * (n - i - 1) + "*" * (i + 1)
            if i < n - 1:
                s += "\n"
        return s

# Create solution object and test
ob = Solution()
result = ob.solve(5)
print(result)

The output of the above code is ?

    *
   **
  ***
 ****
*****

Alternative Approach Using List Join

We can also use a list comprehension with join for a more concise solution ?

def create_triangle_stairs(n):
    stairs = []
    for i in range(n):
        spaces = " " * (n - i - 1)
        stars = "*" * (i + 1)
        stairs.append(spaces + stars)
    return "\n".join(stairs)

# Test the function
n = 5
result = create_triangle_stairs(n)
print(result)

The output of the above code is ?

    *
   **
  ***
 ****
*****

One-Line Solution

For a more compact approach using list comprehension ?

def triangle_stairs_oneline(n):
    return "\n".join(" " * (n - i - 1) + "*" * (i + 1) for i in range(n))

# Test the one-line solution
n = 6
print(triangle_stairs_oneline(n))

The output of the above code is ?

     *
    **
   ***
  ****
 *****
******

How It Works

The pattern works by calculating two components for each row:

  • Spaces: (n - i - 1) spaces for right-alignment
  • Stars: (i + 1) stars for the current step

For n=5, row 0 has 4 spaces + 1 star, row 1 has 3 spaces + 2 stars, and so on until row 4 has 0 spaces + 5 stars.

Conclusion

Creating triangle stairs with stars involves calculating the right number of spaces and stars for each row. The list comprehension approach provides a clean, readable solution for generating the pattern.

Updated on: 2026-03-25T10:37:39+05:30

727 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements