2

I am trying to make a program that will print a pattern such as:

n = 4

    1
   12
  123
 1234

Right now this is what I have:

n = int(input("Please enter a positive integer: "))
line = ""
for currentNum in range(1,n+1):
    line = " " * (n-currentNum) + line + str(currentNum)
    print(line)

I am not getting the right amount of spaces that I'm hoping that I would get. Any tips? Thanks.

This is what I'm getting on IDLE:

    1
       12
         123
          1234
          12345
2
  • That's because you need to know the max length of the final number before you start iterating and then subtract a space from the max length for each value Commented Oct 23, 2015 at 15:46
  • But wouldn't " " * (n-currentNum) take care of that? currentNum starts at 1 and if n is 4, then there should be 3 spaces for line 1 Commented Oct 23, 2015 at 15:50

4 Answers 4

3
for i in range(1, n+1):
    print(" "*(n-i) + "".join(map(str, range(1, i+1))))
Sign up to request clarification or add additional context in comments.

Comments

0

There's a much easier way to do this with .rjust.

n = int(input("Please enter a positive integer: "))
line = ''
for current_num in range(1, n+1):
    line += str(current_num)
    print(str(current_num).rjust(n, ' '))

Or as a one liner to play off of Eugene's answer:

n=int(input());print('\n'.join(''.join(map(str,range(1,i+1))).rjust(n,' ')for i in range(1,n+1)))

1 Comment

I will look into that, but as of now I'm not allowed to use such syntax for class
0

The problem is you are appending the spaces and numbers to line each time. You just want to append the numbers and print with the added spaces. If you can't use other functions then something like this will work:

n = int(input("Please enter a positive integer: "))
line = ""
for currentNum in range(1,n+1):
    line += str(currentNum)
    spaced_line = ' '*(n-currentNum) + line
    print(spaced_line)

Comments

0
for i in range(0,n+1):
    print(f"{' '*(n - i)}{''.join([str(x) for x in list(range(1,i+1))])}")

Try to avoid concatenating for effective memory management.

Comments

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.