Drawing a hollow asterisk square

前端 未结 10 1587
情话喂你
情话喂你 2020-12-09 14:09

I\'m trying to figure out how to turn my whole square into a hollow one. The few things I\'ve tried so far haven\'t been very successful as I end up getting present

相关标签:
10条回答
  • 2020-12-09 14:45

    Here is my python code for drawing a square by entered size N.

    n = int(input())
    print('*' * n)
    for i in range(n-2):
        print ('*' + ' ' * (n-2) + '*')
    print('*' * n)
    

    Basically the first and the last print('*' * n) are drawing the top and the bottom lines and the for cycle prints the body.

    Output example: N=3

    ***
    * *
    ***
    

    Output example: N=5

    *****
    *   *
    *   *
    *   *
    *****
    
    0 讨论(0)
  • 2020-12-09 14:51
    def emptySquare(length,char):
        for i in range(length):
            for j in range(length):
                if (i == 0 or i == length-1 or j == 0 or j == length-1):
                    print(char,end=" ")
                else:
                    print(" ",end=" ")
            print()
    
    0 讨论(0)
  • 2020-12-09 14:53

    I think this is what you want to do:

    m, n = 10, 10
    for i in range(m):
        for j in range(n):
            print('*' if i in [0, n-1] or j in [0, m-1] else ' ', end='')
        print()
    

    Output:

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

    You can also draw a triangle this way:

    m, n = 10, 10
    for i in range(m):
        for j in range(n):
            print('*' if i in [j, m-1] or j == 0 else ' ', end='')
        print()
    

    Output:

    *         
    **        
    * *       
    *  *      
    *   *     
    *    *    
    *     *   
    *      *  
    *       * 
    **********
    
    0 讨论(0)
  • 2020-12-09 14:53

    Heres my example:

    print("Enter width")
    width = int(input())
    print("Enter height")
    height = int(input())
    
    for i in range(height):
        if i in[0]:
            print("* "*(width))
        elif i in[(height-1)]:
            print("* "*(width))
        else:
            print("*"+"  "*(width-2)+" *")
    
    input()
    

    Output: Image link

    Hope this helps everyone else, who wants to leave spaces between asteriks, while printing a rectangle and if there are any mistakes in my code let me know, because I'm a beginner myself.

    0 讨论(0)
提交回复
热议问题