# Using Python to Create a Regular Triangle

I am confused and frustrated as to why my program is not doing the way it should. I am trying to create a right triangle using asterisks in python ver 3. I am using the exact code from the tutorial and it comes out as a straight line. Please enlighten me.

Example

``````size = 7

for row in range (size):
for col in range (row + 1):
print('*', end='')
print()
```

```

``````*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
```

```

all in one column

+3

source to share

In Python, indents are counted. The final one `print`

should be aligned with the second `for`

.

``````size = 7

for row in range (size):
for col in range (row + 1):
print('*', end='')
print()
```

```

Result:

``````*
**
***
****
*****
******
*******
```

```

An empty `print`

function effectively means "go to new line". if both statements `print`

are executed with the same indentation level, then every time you type an asterisk, you go to the next line. If the second `print`

goes outside the inner loop `for`

, you only get 7 new lines.

+7

source

alternatively you can use one loop `for`

!

``````>>> s=''
>>> for i in range(7):
...  s+='*'
...  print (s)
...
*
**
***
****
*****
******
*******
```

```
+1

source

This may not be the most readable solution, but if you fancy oneliners, this is one way to do it:

``````print "\n".join(["".join(["*" for col in range(row+1)]) for row in range(7)])
```

```

EDIT

Just to make it even shorter:

``````print "\n".join(["*" * (row+1) for row in range(7)])
```

```
+1

source

All Articles