1

I'm using python IDE wing version 4.1

I'm trying to write a function with only 1 input which will be an integer and return the next shape of stars:

  *
 **
***

I tried using the following code but it gave another shape:

from math import *
from string import *
def tri_1(n):
    x=n*'*'
    i=0
    while i<5:
        x=i*'*'
        i=i+1
        print x

n=input()
tri_1(n)

2 Answers2

0

You need to think more carefully about what the algorithm should do. For each integer in the range 1 to n inclusive you want to print n-1 spaces followed by n asterisks, so what is the hard-coded 5 doing there? Why don't you have any spaces? Given that you know how many times you will loop, why use while rather than for?

The most efficient way to achieve this is using the built-in string method rjust, which pads the supplied string with spaces:

def tri_1(n):
    for i in range(1, n+1):
        print(str.rjust("*"*i, n))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
-1

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')
timgeb
  • 76,762
  • 20
  • 123
  • 145