For problems like these, try to associate the output with its indices (or in this case, current_row
). Also, it seems like it’s better to start from 0 for this one.
0: 1
1: 2 * 3
2: 4 * * * 5
3: 6 * * * * * 7
4: 8 * * * * * * * 9
max_row
is 5, current_row
is from 0 to 4.
There are max_row - current_row - 1
spaces on each row.
There are 2 * current_row - 1
stars on each row.
The numbers on the left is just twice current_row
, or 2 * current_row
. This is true for all except 0. We could use an if statement for that special case.
The numbers on the right is just left + 1
, or 2 * current_row + 1
.
space="\t"
star="*"
size = int(input("Enter number to make triangle: "))
def printRow(current_row, max_row) :
star_count = 2 * current_row - 1
line = space * (max_row - current_row - 1)
if current_row == 0 :
line += "1"
else :
line += str(2 * current_row) + space
line += (star + space) * star_count
if current_row > 0 :
line += str(2 * current_row + 1)
print(line)
if size <= 0 :
print("The value you entered is too small to display a triangle")
for i in range(0, size) :
printRow(i, size)
solved How do I size and sapce