使用循环创建菱形图案

2024-09-27 07:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个程序,它读取一个整数,并使用星号显示给定边长的填充菱形。例如,如果边长是4,程序应该显示

   *
  ***
 *****
*******
 *****
  ***
   *

这就是我要做的。它正在执行,但我似乎无法为程序正确地显示菱形形状而获得正确的空格。。。。

userInput = int(input("Please input side length of diamond: "))

if userInput > 0:
    for i in range(userInput):
        for s in range(userInput -3, -2, -1):
            print(" ", end="")
        for j in range(i * 2 -1):
            print("*", end="")
        print()
    for i in range(userInput, -1, -1):
        for j in range(i * 2 -1):
            print("*", end="")
        print()

谢谢你!


Tags: in程序forinputrange整数星号int
3条回答

谢谢各位,我能够根据我得到的帮助来制定/修正我的代码。感谢大家的投入和帮助,所以社区!

if userInput > 0:              # Prevents the computation of negative numbers
    for i in range(userInput):
        for s in range (userInput - i) :    # s is equivalent to to spaces
            print(" ", end="")
        for j in range((i * 2) - 1):
            print("*", end="")
        print()
    for i in range(userInput, 0, -1):
        for s in range (userInput - i) :
            print(" ", end="")
        for j in range((i * 2) - 1):
            print("*", end="")
        print()

这可能对您更有效:

n = userInput

for idx in range(n-1):
    print((n-idx) * ' ' + (2*idx+1) * '*')
for idx in range(n-1, -1, -1):
    print((n-idx) * ' ' + (2*idx+1) * '*')

用户输入的输出=6:

      *
     ***
    *****
   *******
  *********
 ***********
  *********
   *******
    *****
     ***
      *

以下几点怎么样:

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))

给予:

     *
    ***
   *****
  *******
 *********
***********
 *********
  *******
   *****
    ***
     *

那么它是如何工作的呢?

首先我们需要一个计数高达side的计数器,然后再返回。没有什么能阻止您将两个范围列表附加在一起,因此:

list(range(3)) + list(reversed(range(3-1))

这给了你一个列表[0, 1, 2, 1, 0]

从这里开始,我们需要为每一行计算出正确的空格和星号:

  *        needs 2 spaces 1 asterix
 ***       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}}")

相关问题 更多 >

    热门问题