python - Python 中使用嵌套循环的两位数乘法表

标签 python python-2.7 for-loop nested-loops

我正在尝试学习嵌套循环,所以我想制作一个简单的乘法表,你能帮我改进我的代码吗?

for i in range(1,10):
    print("i =", i, ":")
    for j in range(1, 10):
        print (i*j)

我的程序在运行时看起来非常困惑,如何将结果对齐为矩阵/表格之类的内容以使其更易于阅读?

最佳答案

如果您使用的是Python 2.x,print是一条语句,因此您需要确保打印当前行后该行不会结束。 format 函数中的 {:2d} 可确保始终有两位数的空间。如果您更喜欢 0 而不是空格,则可以使用 {:02d}

for i in range(1, 10):
    print "i =", i, ":",                   # Note the comma at the end
    for j in range(1, 10):
        print "{:2d}".format(i * j),       # Note the comma at the end
    print

输出

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

print 进行一些小改动,也可以使其在 Python 3.x 中工作。请记住 print 是 Python 3.x 中的一个函数

for i in range(1, 10):
    print("i =", i, ":", end=" ")
    for j in range(1, 10):
        print("{:2d}".format(i * j), end=" ")
    print()

注意:您可以在Format Specification Mini-Language中阅读有关各种字符串格式选项的更多信息。 Python 文档的部分。

关于python - Python 中使用嵌套循环的两位数乘法表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108861/

相关文章:

python - 导入错误 : No module named gtk

r - 向量化 R 中的双重求和

python - 删除除两个特定目录外的所有文件/目录

python - 如何在pytorch中按第一维对张量进行排序?

python - 以可移植数据格式保存/加载 scipy sparse csr_matrix

Javascript:无法停止 setTimeout

C中的循环条件检查

python - 从多维 numpy 数组中选择随机数组并进行替换

python - 无法安装最新版本的 pandas (1.0.3)

c# - 如何将纯文本命令发送到在具有脚本引擎的 win7 上运行的 c# 类?