打印一个Python精美的ASCII钻石,宽度可设置

2024-04-27 13:27:31 发布

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

是的,这是一项家庭作业。但请告诉我,如果你要给我密码,请告诉我你做了什么详细。我对这件事非常陌生。

所以任务是根据用户输入的宽度打印一个ASCII菱形。我可以做钻石的前半部分,只是不能做下半部分,因为某些原因我只是看不到怎么做。

这是我的代码:

wid = int(input("Width: "))
i = 1

while i <= wid:
  print(" " * (wid - i) + "* " * i)
  i = i + 1

如果wid=5,则输出如下:

Width: 5
    * 
   * * 
  * * * 
 * * * * 
* * * * * 

Tags: 代码用户密码input宽度ascii原因width
3条回答

我试图用注释来解释代码。我希望有帮助。

wid = int(input("Width: "))

#no. of lines will be double the width
#each loop prints a line.
for i in range(wid *2):

    #first half of the diamond
    if i<=wid:
        no_of_spaces = wid - i
        no_of_stars = i
        print(" "*no_of_spaces +  "* "*no_of_stars) 

    #next half of the diamond
    else:
        no_of_spaces = i - wid
        no_of_stars = 2*wid - i
        print(" "*no_of_spaces +  "* "*no_of_stars) 

你从i = 1开始,一直到i > wid为止。要做钻石的底部,你必须做与顶部相反的事情。代码很简单,但除非你想让我写,否则我不会写。

 i=1
 j=input("ENTER NO =")
 l=0
 for i in range(i,j-((j/2)-1),1):
     print (' ' * ((j+1)/2-i)+'*' *(i*2-1))
     l=(j/2+1)
     while  (i==l):
        i=1
        for i in range(i,j,1):
            print (' ' *((i*2)-i)+'*' *(j-i*2))
        if [i==j-1]:
            l=raw_input('<press enter to exit>')       

相关问题 更多 >