JamesCornel
JamesCornel

Reputation: 35

Nested Loops "For" in Python : Order T

I'm beginner in Python. I am having difficulty resolving my problem:

Using nested for loops, print a right triangle of the character T on the screen where the triangle is one character wide at its narrowest point and seven characters wide at its widest point:

T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT

and

      T  
     TT
    TTT
   TTTT
  TTTTT
 TTTTTT
TTTTTTT

Any idea?

Upvotes: 0

Views: 1002

Answers (2)

Pralhad Narsinh Sonar
Pralhad Narsinh Sonar

Reputation: 1454

I hope you already have got the answer :)

Pattern # 1

def triangle(n):
    for i in range(1, n +1):
        print ('T' * i).rjust(n, ' ')

triangle(7)

##Results >>>

      T  
     TT
    TTT
   TTTT
  TTTTT
 TTTTTT
TTTTTTT

Pattern # 2

def triangle1(n):
    for i in range(1, n +1):
        print ('T' * i)

triangle1(7)

# Results >>>>
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT

Pattern generation by using only for loops

Here I have tried to generate the with the help of only for loops and will very generalized way. Purposefully I have not used any readily available functions so you can always optimize it further.

Pattern # 1

def triangle(n):
    # Iterate through number of columns
    for i in range(1, n +1):
        s = ""
        # Iterate through number of rows
        for j in list(range(i)):
            s += "T"
        print s

triangle(7)

Pattern # 2

def triangle1(n):
    # Iterate through number of columns
    for i in range(1, n +1):
        s = ""
        # Iterate through number of rows
        for j in list(range(i)):
            blank = ""
            # Generate 'blank spaces'
            for k in (range(n - i)):
                blank += " "
            # Generate 'T'
            s += "T"
        print blank + s

triangle1(7)

Upvotes: 1

MateuszPrzybyla
MateuszPrzybyla

Reputation: 897

I won't write a code for you but I can give you some hints:

  • nested loops means a loop inside another loop, in this case one loop is for iterating through consecutive lines, the second is to print characters in each line
  • the second example needs the same as the first, but you also need to check index of the inner loop and decide whether print space or 'T' character

Upvotes: 5

Related Questions