在此 Python 程序中,您将学习如何使用 for 循环、while 循环和函数来打印字符串文本的字母或单个字符,以递增列的右角三角形模式打印。
下面的示例程序使用 for 循环迭代给定字符串中的每个字符,并以右角三角形模式打印它们。如果您查看输出,它会在每一行添加一个新字符。
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
此程序使用 while 循环代替 for 循环来迭代字符串文本,并以右角三角形模式打印递增的字母。下面的示例接受用户输入的文本并显示输出。
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
这个 Python 程序允许用户输入行数和字母字符。接下来,rightTriangleSameChar 函数使用嵌套的 for 循环来打印给定字符的右角三角形,按行和列打印。
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)
