In this Python program, you will learn to print the letters or individual characters of a string text in a right angled triangle pattern of incrementing columns using for loop, while loop, and functions.
The below example program uses the for loop to iterate each character in a given string and prints them in a right angled triangle pattern. If you look at the output, it adds a new character in each row.
text = 'Tutorial Gateway'
a = ''
for i in text:
a += i
print(a)
T
Tu
Tut
Tuto
Tutor
Tutori
Tutoria
Tutorial
Tutorial
Tutorial G
Tutorial Ga
Tutorial Gat
Tutorial Gate
Tutorial Gatew
Tutorial Gatewa
Tutorial Gateway
Instead of a For loop, this program uses the while loop to iterate the string text and prints the incremented letters in the right angled triangle pattern. The below example accepts the user-entered text, and display the output.
text = input("Please Enter Your Own String : ")
a = ''
i = 0
while i < len(text):
a += text[i]
print(a)
i += 1
Please Enter Your Own String : Hello World
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World
This Python program allows the user to enter the rows and the alphabet characters. Next, the rightTriangleSameChar function uses nested for loops to print the right angled triangle of a given character on rows and columns.
def rightTriangleSameChar(rows, a):
for i in range(rows):
for j in range(i + 1):
print('%c' %a, end=' ')
print()
rows = int(input("Enter Rows = "))
a = input("Enter Character = ")
rightTriangleSameChar(rows, a)