Trying to print a set of numbers that are right justified without using format

36 Views Asked by At

I am trying to write the following code: Write a program that accepts a number, n, where -6<n<2. The program will print out the numbers n to n+41 as 6 rows of 7 numbers. The first row will contain the values n to n+6, the second, the values n+7 to n+7+6, and so on.

However, when it comes to a single digit on the first line the alignment goes out. Why does this happen and how can I fix it?

n = int(input("Enter a number between -6 and 2:"))

if n > 2:
    print("Invalid input! The value of 'n' should be between -6 and 2.")
elif n <-6:
     print("Invalid input! The value of 'n' should be between -6 and 2.")
else:
    for i in range(n,n+42,7):
        for j in range(i,i + 6):
            if -1<j<10:
                print(" " + str(j), end = " ") 
            else: 
                print(j, sep = " ",end= " ")
        print((i+6))

output: 
 2  3  4  5  6  7 8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 32 33 34 35 36
37 38 39 40 41 42 43
2

There are 2 best solutions below

0
OldBoy On

It is because you do not correctly space the last column; even though it looks correct for every line after the first. So instead of printing the last number after the inner loop complets, print all the numbers in that loop, and then a blank to terminate the line; as follows:

for i in range(n,n+42,7):
    for j in range(i,i + 7):  # print all 7 columns
        if -1<j<10:
            print(" " + str(j), end = " ") 
        else: 
            print(j, sep = " ",end= " ")
    print('') # terminate the final line 
0
Xero Smith On

Instead of the double for loop, you can iterate over the numbers you want to print just once. There are 2 main points to keep in mind.

  1. You want all numbers to have the same string width. Negative and double digit numbers have string length 2. Thus, you need to pad single digit numbers with a leading space so its string length becomes 2 and right justified.

  2. We put a new line after every seventh number we print. For this, we check how many we have printed so far using modular arithmetic.

Putting these 2 ideas together, we get the follwing implementation:

def solve(n):
    for i, j in enumerate(range(n, n+42)):  # Enumerate keeps explicit count of the elements in an iterable
        s = str(j)
        if len(s) < 2:                      # Test to normalise the string length of numbers for printing
            s = ' ' + s                     # Space before `s` means `s` is right justified 
        if (i + 1) % 7:                     # Test for the line ending character
            nl = ' '                        
        else:
            nl = '\n'
        print(s, end=nl)