1

I'm trying to do this triangle in Python as an assignment for my computer science class, but I quite can't figure it out. The output is supposed to be like this:

Select your height. > 5

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

But it comes out like this:

Select your height. > 5

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

Here's the source code.

I apologize for the lengthiness and slight unruliness, I'm currently using vim as my text editor, and I'm fairly new at it. I'm so sorry if this question is bad... I searched for Python's documentation page, and I tried .ljust() and .rjust(), and it doesn't seem to be working for me well. Thanks so much for your help in advance!

# The tools we will use:
# We're just using this to make the program have a more clean, organized feel when executing it.
import time

# This will help build the triangle, along with other variables that will be described later. Spacing is necessary to help build a presentable triangle.
asterisk = "* "

# added will be used in the loop to control how long it will keep repeating the task.
added = 0

# This will multiply the amount of asterisks so that every time a line passes during the loop, it will steadily increase by one.
multiplier = 2

tab = ("""\t\t""")
nextline = ("""\n\n""")


# the finished product!

triangle = ("""""")



# THE PROCESS

print("I will ask you for a height -- any height. Once you tell me, I'll make an isosceles triangle for you.")

#time.sleep(2)

height = input("Please enter a height. > ")


heightNum = int(height)



while heightNum <= 0:

        print ("Oops, you can't insert negative numbers and zeroes. Please try another one!")
        height = input("Please enter a height. > ")
        heightNum = int(height)



while heightNum > added:

        if added == 0:
                triangle = (tab + triangle +  asterisk + nextline)
                added += 1


        else:
                starsline =(tab + asterisk * multiplier + nextline)
                triangle  = (triangle + starsline)

                added += 1
                multiplier += 1


print("Here it is! \n\n\n")
print(triangle)

print ("\n\nThis triangle is %d asterisks tall.") % heightNum                                                                                
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
tatsumaki
  • 13
  • 2
  • 2
    Hint - Your first line is an asterisk followed by four spaces, but expected output is four spaces followed by an asterisk. – shree.pat18 Mar 21 '14 at 21:53
  • @shree.pat18, you mean that I should replace the tab variable and add a tab escape for the asterisk variable instead? I tried it out right now, but it's not working... Again, sorry if I'm being unhelpful here. – tatsumaki Mar 21 '14 at 22:04
  • What I mean is, there is a relation between the row number and the number of asterisks that should be printed, starting from the right. – shree.pat18 Mar 21 '14 at 22:07

2 Answers2

0
def print_triangle(length):
    for i in range(1, length+1):
         print('{0:>{length}}'.format('*'*i, length=length))

And usage:

>>> print_triangle(5)
    *
   **
  ***
 ****
*****

To break it down, this is using the string formatting mini-language:

 '{0:>{length}}'

The first opening bracket is indexed to the first argument, and the : means that formatting specifications will follow it. The > means to right justify it by a width, which is provided by another keyword variable, the length of the triangle.

That should be enough to get you finished, without rewriting your entire script.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
  • THank you so much! It worked! However, I just want to ask you a couple of questions to make sure I understood the code well. What you meant to do with the for loop is the following: if length is equal to 5, then repeat the following code 6 times (because if you leave it as length alone, it'll always be one line short). Then you wrote '{0:>{length}} so that starting from the 0th space, everything that's written there will be put to the left. Then, by taking advantage of the for loop that keeps going up by one number, you just multiply i by the asterisk string and keep length's values. – tatsumaki Mar 22 '14 at 15:31
  • @tatsumaki `range` starts at zero by default, so I tell it to start at one. It ends at the second argument (if given more than one argument) so I tell it to go up to and not including one more than how long we want it to be (so it goes to exactly how long we want it to be.) So it simply cycles from 1 to 5 inclusive. **It only goes through the code 5 times in the above example!** The rest of what you said is correct. – Russia Must Remove Putin Mar 22 '14 at 15:41
  • Awesome! Thanks, @Aaron, and everyone else! :) – tatsumaki Mar 22 '14 at 16:32
0
def triangle(n):
  return '\n'.join(
      '%s%s' % (' ' * (n - i), '*' * i)
      for i in xrange(1, n + 1))

print triangle(5)

This works because

'x' * n is a string with n 'x''s concatenated together which the '%s%s' % ... line uses to produce one row of n characters with spaces at the left and asterisks at the right.

'\n'.join(...) joins a generator expression on a newline to combine the rows into a triangle.

for i in xrange(1, n + 1) uses another generator to iterate a row counter, i, from 1 to n. The n + 1 is there since ranges are half-open in python.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245