【问题标题】:Issue formatting a multiplication table in Python using nested loops使用嵌套循环在 Python 中格式化乘法表
【发布时间】:2022-12-13 00:03:47
【问题描述】:

除了列的顶部标签和列标签下方的下划线外,我已经正确设置了所有格式。我怀疑第一个 for 循环编码不正确,但我不知道我做错了什么。

def main():

    print("This is a times-table.")

    n = int(input("Enter a number: "))
        
    for i in range(1,n+1):
        print(" {:3d}".format(i), end='')
    print()

    for i in range(1, n+1):
        print(i, " |{:3d}".format(i), end='')
        for x in range(1, n+1):
            print("{:3d}".format(i*x), end="")

        print()

main()

Desired Output

【问题讨论】:

  • 输出?期望的输出?
  • 我在帖子中添加了所需输出的照片。

标签: python for-loop nested-loops


【解决方案1】:
def main():

    print("This is a times-table.")

    n = int(input("Enter a number: "))
        
    for i in range(1,n+1):
        print(" {:3d}".format(i), end='')
    print()

    for i in range(1, n+1):
        print(i, " |{:3d}".format(i), end='')
        for x in range(2, n+1):
            print("{:3d}".format(i*x), end="")

        print()

main()

它位于 x for 循环中,您需要从 2 开始。这是因为,在其上方的 for 循环中,您已经通过声明 |{:3d} 设置了第一个数字。你可以删除它,或者从 2 开始。

此外,您可能希望通过在正确位置的列上方设置数字来改进这一点。

【讨论】:

  • 将其更改为 2 并没有改变我的输出。它根本没有移动第一行:/
【解决方案2】:

对于范围 (0, 10) 中的行: 对于范围 (0, 10) 中的列: 数 = 行 * 列 如果数字 < 10: 空=“” 别的: 如果 num < 100: 空=“” 如果 col == 0: 如果行 == 0: 打印(“”,结束='') 别的: 打印(“”,行,结束='') elif 行 == 0: print(" ", col, end='') 别的: 打印(空,数字,结束='') 打印()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多