As this seems to be a basic programming exercise, I don't think we should rely on in-built functions too much. The following function gets the idea across.
def print_triangle(n):
for i in range(1, n+1):
for j in range(n-i):
print(' ', end='')
for k in range(i):
print('*', end='')
print()
Invoking print_triangle(3)
will print
*
**
***
This function is a little shorter, but does the same thing.
def print_triangle2(n):
for i in range(1, n+1):
print(' '*(n-i), end='')
print('*'*i)
Hope that helps.
EDIT:
Thanks Jon, I got so used to the Python 3 print statement that I forgot that the end=''
part would not work unless you are using Python 3. This should work in Python 2.7:
import sys
def print_triangle(n):
for i in range(1, n+1):
for j in range(n-i):
sys.stdout.write(' ')
for k in range(i):
sys.stdout.write('*')
sys.stdout.write('\n')
def print_triangle2(n):
for i in range(1, n+1):
sys.stdout.write(' '*(n-i))
sys.stdout.write('*'*i)
sys.stdout.write('\n')