Python循环反向钻石

时间:2015-02-13 03:11:17

标签: python loops reverse

我有一个代码循环创建一个钻石,但我希望它能被颠倒。

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]

我的输出如下:

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

但我希望它是这样的:

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

帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

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