Reputation: 43
I'm trying to print a half pyramid that stars on the left side in python. So far, this is my code
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in range(1, i):
print(j, end = " " )
print("\n")
and my output is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
However, my output is meant to be in the opposite order:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How can I make this change?
Upvotes: 1
Views: 2981
Reputation: 351328
Reverse the range by adding the third argument (-1
). Also format your numbers to use 2 places, so 10 is not pushing the last line to the right. Finally, the last print
should probably not have \n
, since that is already the default ending character of print
:
for i in range(1,12):
for j in range(12 - i):
print(" ", end = "")
for j in range(i-1, 0,-1):
print(str(j).rjust(2), end = "" )
print()
Upvotes: 2
Reputation: 310
The problem is in your second for loop, as you are looping from 1
to i
, meaning you start off with 1 being printed first, and every following number until (not including) i
.
Fortunately, for loops are able to go in reverse. So, instead of:
for j in range(1, i)
You could write:
for j in range((i-1), 0, -1)
Where the first parameter is signifies where the loop starts, the second is where the loop finishes, and the third signifies how large our jumps are going to be, in this case negative. The reason we are starting at i-1
and finishing at 0
is because loops start at exactly the first given number, and loop until just before the second given number, so in your given code the loop stops just before i
, and so this one starts just before i
as well, although you could remove the -1
if you wish to include 12 in the pyramid.
Upvotes: 0
Reputation: 21619
You could just reverse the range that you print out as numbers
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in reversed(range(1, i)):
print(j, end = " " )
print("\n")
Upvotes: 1
Reputation: 77910
Just reverse the second loop -- the one that prints that actual numbers:
for j in range(i-1, 0, -1):
The last parameter controls the "step", or how much the variable changes on each loop iteration. Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
...
Upvotes: 2