Search code examples
pythonnested-loops

I cant get my code to draw a number pattern with nested loops in Python that will align all number printouts in a neat manner


Use nested for loops to create the following printout:

enter image description here

The number of rows should be read from the user. Use formatted printouts so that the numbers are aligned even for two-digit numbers. • All printed numbers correspond to column numbers. • No number is printed if the column number is less than the row number. • Print a suitable number of spaces to fill an empty column.

# Program to print a pattern with numbers

print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)

for i in range(n + 1):
    # Increase triangle hidden
    for j in range(i):
        print(" ", end=' ')
    #  Decrease triangle to include numbers in pattern not in increment
    for j in range(i, n):
        print(j + 1, end=" ")
    print()

The code above produces the required output but the numbers are not aligned in an input with 2 digits. How do I format the iterables to make a perfectly aligned output printout.

Output: enter image description here


Solution

  • This is how you might modify your code to use str.rjust. Adjust the 2 in rjust(2) to whatever number you want.

    print("Program to print a pattern with numbers ")
    print("-" * 50)
    n = int(input("Please enter the number of rows "))
    print("-" * 50)
    
    for i in range(n + 1):
        # Increase triangle hidden
        for j in range(i):
            print(" ".rjust(2), end="  ")
        #  Decrease triangle to include numbers in pattern not in increment
        for j in range(i, n):
            print(str(j+1).rjust(2), end="  ")
        print()
    

    For your example, this gives:

    Program to print a pattern with numbers 
    --------------------------------------------------
    Please enter the number of rows 12
    --------------------------------------------------
     1   2   3   4   5   6   7   8   9  10  11  12  
         2   3   4   5   6   7   8   9  10  11  12  
             3   4   5   6   7   8   9  10  11  12  
                 4   5   6   7   8   9  10  11  12  
                     5   6   7   8   9  10  11  12  
                         6   7   8   9  10  11  12  
                             7   8   9  10  11  12  
                                 8   9  10  11  12  
                                     9  10  11  12  
                                        10  11  12  
                                            11  12  
                                                12