In this post, we will learn how to print triangle patterns in Python using single for loop. Here we cover both left and right triangle patterns with detailed explanations and examples.

These pattern programs are very helpful from an interview point of view because writing efficient code creates a good impression on interviewers.

So let’s start writing code and understand how we can achieve our goal using a single for loop.

Left Triangle Pattern

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

Source Code

num = int(input("Enter number of rows: "))

for i in range(1, num+1):
    print("* "*i)

Explanation

  • We take the number of rows as input from the user.
  • We use a single for loop that runs from 1 to the number of rows.
  • In each iteration, we print i stars followed by a space.

Right Triangle Pattern

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

Source Code

num = int(input("Enter number of rows: "))

for i in range(1, num + 1):
    print('  ' * (num - i) + '* ' * i)

Explanation

  • We take the number of rows as input from the user.
  • We use a single for loop that runs from 1 to the number of rows.
  • In each iteration, we print spaces followed by stars. The number of spaces decreases while the number of stars increases.

Hope you now know how simple it is to print left and right triangle patterns in Python using a single for loop. Thank you for reading this article. See you in the next one.

For more pattern programs check this article πŸ‘‰ Pattern programs in python.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment