Python中的数字对齐

问题描述 投票:0回答:4

指令:编写一个程序,为数字1-10生成乘法表。使用两个for循环来完成您的程序。您将需要在另一个for循环中放置一个for循环。作为额外的挑战,请看是否可以使缩进看起来正确。因此,程序的输出应为:

enter image description here

我的代码:

# Start a for loop from 1 to 10.

for num1 in range(1, 10):

# Start a nested loop from 1 to 10.

    for num2 in range(1, 10):

    # Display the multiplication for each value of num.

        print('%4d'%(num1*num2), end = '')

# Display new line after inner for loop finished.

print()

数字需要像上面说明中的图片一样对齐。我的只是直射整个屏幕。我不确定自己在做什么错。

这是我的样子:

enter image description here

python
4个回答
0
投票
for num1 in range(1, 10): print() for num2 in range(1, 10): if len(str(num1*num2)) == 1: print(" "+str(num1*num2),end = ' ') else: print(str(num1*num2),end = ' ')

输出:

 1  2  3  4  5  6  7  8  9 
 2  4  6  8 10 12 14 16 18 
 3  6  9 12 15 18 21 24 27 
 4  8 12 16 20 24 28 32 36 
 5 10 15 20 25 30 35 40 45 
 6 12 18 24 30 36 42 48 54 
 7 14 21 28 35 42 49 56 63 
 8 16 24 32 40 48 56 64 72 
 9 18 27 36 45 54 63 72 81 

0
投票
我添加了if语句,当第二个循环用完要打印的元素时,该语句将打印新行

0
投票
# Start a for loop from 1 to 10. for num1 in range(1, 10): # Start a nested loop from 1 to 10. for num2 in range(1, 10): # Display the multiplication for each value of num. print('%4d'%(num1*num2), end = '') # Display new line after inner for loop finished. print("\n") # change made here

0
投票
# Start a for loop from 1 to 10. for num1 in range(1, 10): # Start a nested loop from 1 to 10. for num2 in range(1, 10): # Display the multiplication for each value of num. print('%4d'%(num1*num2), end = '') print ('\n') # Display new line after inner for loop finished.
© www.soinside.com 2019 - 2024. All rights reserved.