1

I'm doing patterns in python but i can't seem to get a this pattern to change.

print("\nPattern C")

for c in range(1, 7 + 1):
    for cc in reversed(range(1, c)):
        print(cc, end = '')
    print('')

This outputs:

Pattern C

1
21
321
4321
54321
654321

But i want it to output:

     1
    21
   321
  4321
 54321
654321

Can anyone help please?

0

4 Answers 4

1

You will have to add spaces in some way. One way is to subtract the current counter from a fixed value and print that many spaces.

for c in range(1, 7 + 1):
    print(' '*(7-c), end='')
    for cc in reversed(range(1, c)):
        print(cc, end = '')
    print('')

As Aaron Hall mentions in comments, there are other ways to produce this output. For example, with a single print() (and num representing the 7+1 value above, and the reversed() replaced with a different range() object):

for c in range(1, num):
    print(' '*(num-1-c), *range(c-1, 0, -1), sep='')
Sign up to request clarification or add additional context in comments.

Comments

0

This is what i would do (while also changing your code as little as possible)

print("\nPattern C")
maxLength = 7
for c in range(1, maxLength + 1):
    s = ''
    for cc in reversed(range(1, c + 1)):
        s += str(cc)
    print(("%" + str(maxLength) + "s")%s)`

I didn't change much, I just added string formatting, and I added a "+ 1".

This uses string formatting to right justify each string. %10s justifies a word to the end of a 10 character space.

Comments

0

I would use a format string method after each line to add the space padding.

print("\nPattern C")

for c in range(1, 7+ 1):
    line=""
    for cc in reversed(range(1, c)):
        line+=str(cc)
    print('{:>6}'.format(line))

Comments

0
N = int(input())
for i in range(N):
    Num = ""
    for j in range(1, i + 2):
        Num = str(j) + Num
    print(" " * (N - i) + (Num))


Input:-6
Output: 
         1
        21
       321
      4321
     54321
    654321

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.