lundi 30 mars 2020

Nested-loop odd pattern in Python

I want to make a pattern as shown below:

N = 1
*

N = 3
  *
***
  *

N = 5
    *
  ***
*****
  ***
    *

and so on...

Nevertheless, I write this program only works for N = 5. Could anybody please explain what the mistake is and what the solution is? Thanks.

N = int(input())
k = 1
for i in range(1, N - 1):
    for j in range(1, N + 1):
        if(j <= N - k):
            print(' ', end = '')
        else:
            print('*', end = '')
    k = k + 2
    print()

k = 2
for i in range(1, N - 2):
    for j in range(1, N + 1):
        if(j >= N - k):
            print('*', end = '')
        else:
            print(' ', end = '')
    k = k - 2
    print()

Aucun commentaire:

Enregistrer un commentaire