gpt4 book ai didi

Python 循环反向菱形

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:11 25 4
gpt4 key购买 nike

我有一个循环创建钻石的代码,但我希望它被反转。

width = int(input("Please enter a width: "))

i = 1
while i < width*2:
if i < width:
print("-" * (width-i) + " *" * i + "-" * (width-i))
else:
print("-" * (i-width) + " *" * (2*width-i) + "-" * (i-width))
i += 1 [EDIT: formatting mistake]

我的输出如下:

---- *----
--- * *---
-- * * *--
- * * * *-
* * * * *
- * * * *-
-- * * *--
--- * *---
---- *----

但我希望它是这样的:

 * * * * *
- * * * *-
-- * * *--
--- * *---
---- *----
---- *----
--- * *---
-- * * *--
- * * * *-
* * * * *

帮助将不胜感激!

最佳答案

width = int(input("Please enter a width: "))

i = 0
while i < width*2:
if i < width:
print("-" * i+ " *" * (width-i) + "-" * i)
else:
print("-" * ((2*width-i) -1) + " *" * (i - width + 1) + "-" * ((2*width-i) -1))
i += 1

关于Python 循环反向菱形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com