尝试打印右对齐的一组数字而不使用格式化

0 投票
2 回答
34 浏览
提问于 2025-04-14 16:17

我正在尝试写一个程序,这个程序需要接受一个数字n,要求这个数字在-6到2之间。然后程序会打印出从n到n+41的数字,分成6行,每行7个数字。第一行显示n到n+6的值,第二行显示n+7到n+13的值,以此类推。

不过,当第一行有单个数字时,排列就会出现问题。为什么会这样?我该怎么解决呢?

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 个回答

0

与其使用双重 for 循环,不如只遍历一次你想打印的数字。

这里有两个主要的要点需要记住。

  1. 你希望所有的数字在显示时宽度一致。负数和两位数的数字长度都是2。因此,你需要在一位数的数字前面加一个 空格,这样它的长度就变成2,并且右对齐。

  2. 我们在每打印第七个数字后换行。为此,我们使用取模运算来检查到目前为止已经打印了多少个数字。

把这两个想法结合起来,我们就得到了以下的实现方式:

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)
0

这是因为你没有正确地处理最后一列的空格;虽然在第一行之后的每一行看起来都没问题。所以,不要在内层循环结束后再打印最后一个数字,而是要在这个循环中打印所有的数字,然后再加一个空格来结束这一行;具体可以这样写:

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 

撰写回答