python画菱形的代码_python–使⽤循环创建菱形图案以下内容如何:
side = int(input("Please input side length of diamond: "))
for x in list(range(side)) + list(reversed(range(side-1))):
print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
赠送:
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
那么它是怎样⼯作的?
⾸先,我们需要⼀个计数器,计数到⼀边,然后再次向下.没有什么可以阻⽌你将两个范围列表附加在⼀起,所以:
list(range(3)) + list(reversed(range(3-1))
这给你⼀个列表[0,1,2,1,0]
从这⾥我们需要计算出每⾏所需的正确空格数和星号:
* needs 2 spaces 1 asterixpython新手代码图案如何保存
*** needs 1 space 3 asterisks
***** needs 0 spaces 5 asterisks
因此需要两个公式,例如对于side = 3:
x 3-x-1 x*2+1
0 2 1
1 1 3
2 0 5
使⽤Python的字符串格式,可以指定填充字符和填充宽度.这避免了必须使⽤字符串连接.
如果您使⽤的是Python 3.6或更⾼版本,则可以使⽤f字符串表⽰法:
for x in list(range(side)) + list(reversed(range(side-1))):
print(f"{'': <{side - x - 1}} {'':*<{x * 2 + 1}}")

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。