for i in range(0,7):
for j in range(0, 7 - i):
print(" ", end = "")
for k in range(0, 2 * i 1):
print("0", end = "")
print(" ")
I saw this code online to build a pyramid contains "0", I'm confused on why do I need to pint(" ") at the very bottom for the first loop?
CodePudding user response:
You are using print
with end=""
to build the lines character by character without getting to a new line.
To build the pyramid, you need to skip to the next line after a line of zeros, thus the print(" ")
that has a end='\n'
parameter by default
output without the last print:
0 000 00000 0000000 000000000 00000000000 0000000000000
Here is a modification of the code to show you where the separators are:
for i in range(0,7):
for j in range(0, 7 - i):
print(" ", end = "-")
for k in range(0, 2 * i 1):
print("0", end = " ")
print("", end='=\n')
output:
- - - - - - -0 =
- - - - - -0 0 0 =
- - - - -0 0 0 0 0 =
- - - -0 0 0 0 0 0 0 =
- - -0 0 0 0 0 0 0 0 0 =
- -0 0 0 0 0 0 0 0 0 0 0 =
-0 0 0 0 0 0 0 0 0 0 0 0 0 =
Here is a shorter alternative to the initial code to build the lines directly with a single loop:
n=7
for i in range(n):
print(' '*(n-i) '0'*(2*i 1))
output:
0
000
00000
0000000
000000000
00000000000
0000000000000