创建乘法表?

2024-04-20 04:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程的初学者,正在练习如何在Python2.7.5中使用嵌套for循环生成乘法表。 这是我的密码

x=range(1,11)
y=range(1,11)
for i in x:
    for j in y:
        print i*j
    pass

好吧,结果是正确的,但它不像我那样以方阵形式出现希望。拜托帮我改进代码


Tags: 代码in密码for编程rangepass形式
3条回答

Python的print语句默认情况下会在输出中添加新的行字符。我想你应该只在内环后面加一个空格,在外循环的末尾加一个新行字符。在

你可以通过使用

print i * j,   # note the comma at the end (!)

在外循环块的末尾添加一条新行:

^{pr2}$

要了解更多关于尾随昏迷的信息,以及它为什么起作用,请看这里:"How to print in Python without newline or space?"。请注意,它在Python3中的工作方式不同。在

最终代码应该如下所示:

x=range(1,11)
y=range(1,11)
for i in x:
    for j in y:
        print i*j,
    print ''

您还可以查找“\t”特殊字符,以便获得更好的格式(即使是这个旧资源也足够好:https://docs.python.org/2.0/ref/strings.html

你应该不间断地打印。在

x = range(1,11)
y = range(1,11)
for i in x:
    for j in y:
        print i*j,    # will not break the line
    print   # will break the line

您可以添加格式以保持单元格宽度不变

x = range(1,11)
y = range(1,11)
for i in x:
    for j in y:
        # substitute value for brackets
        # force 4 characters, n stands for number
        print '{:4n}'.format(i*j),  # comma prevents line break
    print  # print empty line

相关问题 更多 >