Printing an ASCII diamond with set width in python

前端 未结 7 1706
Happy的楠姐
Happy的楠姐 2020-12-11 13:50

Yes, this is a homework task. But just please, if you\'re going to give me the code please tell me what you\'ve done in detail. I am extremely new to this.

So the ta

7条回答
  •  长情又很酷
    2020-12-11 14:29

    I tried to explain the code with comments. I hope it helps.

    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) 
    

提交回复
热议问题