Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing code to make a triangle

Tags:

python

shapes

I'm a beginner and trying to learn Python by myself. I've been working on coding some basic shape exercises, so far I have the following code to make a diagonal.

size = input('Please enter the size: ')
chr  = raw_input('Please enter the drawing character: ')

row = 1
while row <= size:

    col = 1
    while col < row:
        print ' ', 
        col = col + 1
    print chr

    row = row + 1
print ''

I get this output :

X
 X
  X
   X

I would love some help on how to make this into a triangle like this....

X X X X
  X X X
    X X
      X

Any explanations on how to make the loop necessary for the characters to show up to make the triangle shaped output would be appreciated.

like image 477
user2955471 Avatar asked Nov 05 '13 14:11

user2955471


2 Answers

You can do:

>>> for i in xrange(4):
...     print '  ' * i + 'X ' * (4 - i)
...
X X X X
  X X X
    X X
      X

The value of i goes from 0 to 3 (by using xrange) and it prints the string ' ' (two spaces) i number of times and it prints 'X ' in total (4 - i) number of times. This means it'll print the inverted triangle as desired.

like image 199
Simeon Visser Avatar answered Oct 21 '22 10:10

Simeon Visser


The simplest fix is just to print the character print chr, instead of space print ' ',.

To invert the result vertically a simple change in the condition, from while col < row: to while col < (size - row + 1): will suffice. And finally, to invert it horizontally, add a loop that prints spaces:

size = input('Please enter the size: ')
chr  = raw_input('Please enter the drawing character: ')

row = 1
while row <= size:

    col = 1
    while col < row:
        print ' ',
        col = col + 1

    col = 1
    while col < (size - row + 1):
        print chr, 
        col = col + 1
    print chr

    row = row + 1
print ''

And finally, you can simplify this a bit:

size = input('Please enter the size: ')
chr  = raw_input('Please enter the drawing character: ')

row = 1
while row <= size:

    col = 1
    while col < size:
        if col < row:
            print ' ',
        else:
            print chr,
        col = col + 1
    print chr

    row = row + 1
print ''

Result:

Please enter the size: 4
Please enter the drawing character: x
x x x x
  x x x
    x x
      x

And of course you can make this really simple looking at Simeon Visser's answer.

like image 26
BartoszKP Avatar answered Oct 21 '22 11:10

BartoszKP