钻石与星号使用python while循环

时间:2016-04-05 19:52:41

标签: python while-loop

我的目标是打印一条蟒蛇钻石。这是我尝试过的代码:

height=int(input("Please enter height : "))
row=1
#top half of diamond
while(row<height+1):
     spaces=0
     while (spaces<(height-row)):
           spaces+=1
           print ("",end='')

     j=2*row-1
     while (j>0):
          j=j-1
          print("*",end='')
     row+=1
     print()

row=height-1
#bottom half of diamond
while (row>0):
     spaces=0
     while(spaces<height-row):
          spaces+=1
          print("",end='')
     j=2*row-1
     while(j>0):
          print("*",end='')
          j=j-1
    row=row-1
    print()

此代码似乎只打印钻石的右侧,如下所示:

Please enter height : 5
 *
 ***
 *****
 *******
 *********
 *******
 *****
 ***
 *

如何修复代码以便打印钻石的左侧?

1 个答案:

答案 0 :(得分:2)

print ("",end='')中您的意图是打印空格,但""不是空格,而是空字符串。相反,请尝试print (" ",end='')