<分区>
我无法删除 for
循环中的间距,因为生成模式的数字不相同。
我的代码:
for i in range(1,5):
for j in range(1,i):
print(j)
产生以下结果:
1
1
2
1
2
3
但我想要的输出是:
1
12
123
1234
<分区>
我无法删除 for
循环中的间距,因为生成模式的数字不相同。
我的代码:
for i in range(1,5):
for j in range(1,i):
print(j)
产生以下结果:
1
1
2
1
2
3
但我想要的输出是:
1
12
123
1234
最佳答案
试试这个:
print(j, end='')
end
默认为 \n
(参见 print()
)。另外,一定要在每次外循环迭代结束时打印一个换行符:
for i in range(1,6): # notice that I changed this to 6
for j in range(1,i):
print(j, end='') # added end=''
print() # printing newline here
1 12 123 1234
EDIT I just noticed you were using Python 2.7. Since that's the case, you can use print j,
instead of print(j, end='')
and print
instead of print()
. Note that print j,
will leave spaces between the j
s. If you don't want this, you can import sys
and use sys.stdout.write(j)
instead (see sys
).
Furthermore, if you want to use the Python 3 print function as shown above, you can always
from __future__ import print_function
关于python - 以金字塔图案打印将每个数字放在单独的行上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280905/