Printing Character Triangle using Python


Python is a great programming language for all types of programming tasks. IN today’s code lab, we will print different types of Character triangles using Pytho String. The first program is going to print the following

r
ra
rak
rake
rakes
rakesh

When the input string is : rakesh

The above character triangle can be generated using different methods. One of them is using String Slicing and with for loop. Python String Tutorial can help you a lot to understand String Slicing and accessing a single element.  Tutorial on Python Print statement is another recommended tutorial for you.

name = input('Enter your name :')
for x in range(len(name)):
    print(name[:x+1])

The other character string triangle maybe like this

rakesh
rakes
rake
rak
ra
r

The process will remain the same except we will do it in the reverse order

name =input('Enter your name :')
n=len(name)
for x in range(len(name)):
    print(name[:n-x+1])

Now you can combine both approaches to print a pattern of a wave on the screen like this

r
ra
rak
rake
rakes
rakesh
rakes
rake
rak
ra
r

SO the code is something like this

name =input('Enter your name :')
n=len(name)

for x in range(n):
    print(name[:x+1])
    
for x in range(n):
    print(name[:n-x-1:])

Hope you will like today’s code. If you have any better idea to do this type of problem. Please contact us.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.