Python Shape Printing

Question:

shape Hi everyone, I have an assignment to acquire this shape in Python. I am a beginner, I tried to use nested loops to create this shape but I couldn’t. Could someone help? Thanks a lot. (I couldn’t copy the output exactly I’m sorry)

I used nested for loops, if and else statements in various ways (for example, I’ve tried to write stars at the end of a row) but I couldn’t get the shape. I am editing the post in order to show you my effort. I am really sorry that my output is really different from the wanted one.

len = int(input("enter an odd number: "))
if len % 2 == 0:
    print("enter an odd number")

else:
    row = int((len+1) / 2)
    for i in range (0,len):
        print("#",end="")
    print()

    for i in range(0,row):
        print("*")
        print("*", end=" ")
        for j in range(1,len):
            print("*",end="")

    for i in range(0,len):
        print("#",end="")

for n = 5

#####
*  *
*  *
*  *
 * * 
 * * 
*  *
#####
Asked By: Phoebus Apollon

||

Answers:

This could be one way of solving it:

  • if we define n as the sample input, the shape can be divided into 3 steps of length (n//2) each.
  • Initialization: print('#'*n)
  • Step 1: for i in range(n//2): print('*'+' '*(n-2)+'*')
  • Step 2a: create a print_list: print_list = [k*' ' + '*'+ (n-2-2*k)*' ' + '*' + k*' ' for k in range(n//2)]
  • Step 2b: Now print each line in print_list
  • Step 3: Then print each line in print_list[::-1]
  • End: print('#'*n)

Implemented Code:

n = int(input("enter an odd number: ")) 
if n % 2 == 0: 
    print("enter an odd number") 
else: 
    print("#"*n) 
    for i in range(n//2): 
       print('*'+' '*(n-2)+'*')  
       print_list = [k * ' ' + '*' + (n - 2 - 2*k) * ' ' + '*' + k * ' 'for k in range(n//2)]  
       for p in print_list: print(p)
       for p in print_list[::-1]: print(p)

       print("#"*n)
Answered By: AVManerikar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.