Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid, as shown in the following sample run:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
I have the following:
num = eval(raw_input("Enter an integer from 1 to 15: "))
if num < 16:
for i in range(1, num + 1):
# Print leading space
for j in range(num - i, 0, -1):
print(" "),
# Print numbers
for j in range(i, 0, -1):
print(j),
for j in range(2, i + 1):
print(j),
print("")
else:
print("The number you have entered is greater than 15.")
This yields a misalignment for numbers greater than or equal to 10.
I have tried print(format(j, "4d")) and all the numbers become misaligned.
Any tips?
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…